처음부터 차근차근

Swift 문법 정리 2 본문

프로그래밍/Swift

Swift 문법 정리 2

_soyoung 2021. 9. 17. 16:25
반응형
Optional 타입

 

Optional 타입이란, 값을 Optional(값) 또는 *nil을 가질 수 있는 자료형이다.     *nil : 값이 없는 상태. null과 비슷

선언 or 초기화 예

// 방법1
var number : Int? // nil이 들어감
var number : Int? = 1 // Optional(1)이 들어감

// 방법2
var number : Int! // nil이 들어감
var number : Int! = 1 // Optional(1)이 들어감

 

 

 

 

Optional 타입을 사용하는 이유

 

변수의 값을 반환할 때 변수에 아무것도 들어가있지 않으면 오류가 발생한다.

그래서 이러한 오류를 예방하기 위해 Optional타입을 사용한다.

옵셔널 타입은 변수에 값이 없으면 nil 반환하고, 값이 있으면 Optional(값)을 반환하기 때문에 안전하게 처리가 가능하다.

 

 

 

 

wrapping과 unwrapping

 

 wrapping, unwrapping

위의 그림에서 wrapping, unwrapping 되는 것을 보면 알 수 있듯이 Optional은 래퍼클래스이다.

그래서 기본적으로 Optional은 클래스이기 때문에 nil이 들어갈 수 있는 것이다.

 

 

 

 

강제 언래핑(forced unwrappping)

 

강제 언래핑이란, Optional타입의 변수를 강제로 Int, String같은 일반 자료형 변수로 변환하는 것이다.

방법은 2가지가 있다.

 

1. 변수 앞에 '!'를 붙여 사용하는 방법

var number : Int? = 1
print(number) // Optional(1)이 나온다
print(number!) // 1이 나온다. <-- 강제 언래핑

 

2. 옵셔널 바인딩(optional binding)

if문을 사용하여 언래핑하는 방법이다.

var number : Int? = 1

if let constNum = number { // 상수로 받는 방법
	print(constNum) // 결과 : 1
}
if var varNum = number { // 변수로 받는 방법
	print(varNum) // 결과 : 1
}

옵셔널 변수에 값이 있으면 옵셔널 변수를 언래핑해서 상수(or 변수)에다 대입하고, 값이 없으면 if문을 실행하지 않는다.

(조건이 false가 되기 때문)

 

+ 여러 옵셔널 변수 동시에 언래핑하는 법

var number1 : Int? = 1
var number2 : Int? = 2

if let constNum1 = number1, let constNum2 = number2 { // ,는 &&와 같다.
	print(constNum1, constNum2) // 결과 : 1 2
}

 

 

 

 

Int? 와 Int!의 차이점

 

Int!은 Int?와 다르게 Optional변수로 사용되지 않으면 자동으로 unwrapping된다.

이것을 Implicitly Unwrapped Optional(암시적 언래핑 옵셔널)이라 한다.

var num1 : Int? = 10
var num2 : Int! = 10

var num3 : Int = num1 // error
var num4 : Int = num2 // 얘는 됨. 강제 언래핑해서 10이 들어감
var num4 : Int = num2 + 1 // 이것도 된다. 11

 

 

 

 

인스턴스

 

class로부터 만들어진 클래스 객체를 instance라 한다.

 

 

 

 

업캐스팅, 다운캐스팅

upcasting, downcasting

부모 클래스 자료형에서 자식 클래스 자료형으로 변환하는 것을 downcasting이라고 하고,

자식 클래스 자료형에서 부모 클래스 자료형으로 변환하는 것을 upcasting이라고 한다.

 

 

 

 

타입 캐스팅(Type casting)

 

타입 캐스팅에는 두가지가 있다.

 

  1. 업/다운 캐스팅(as, as?, as!)
  2. 타입 검사(is) 이다.

 

1. upcasting

자식클래스 자료형 -> 부모클래스 자료형

사용하는 연산자 : as

class Parent { }
class Child : Parent { }

let parent : Parent = Parent()
let child : Child = Child()

if let upcasting : Parent = child as Parent {
    print("Upcasting was successful")
}
else {
    print("Upcasting was failed")
}
//결과 : Upcasting was successful

child as Parent는 child를 Parent클래스로 업캐스팅할 수 있냐는 뜻이다.

업캐스팅은 항상 성공한다.

 

 

2. downcasting

부모클래스 자료형 -> 자식클래스 자료형

사용하는 연산자 : as!, as?

class Parent { }
class Child : Parent { }

let parent : Parent = Parent()
let child : Child = Child()

if let downcasting = parent as? Child {
    print("Downcasting was successful")
}
else{
    print("Downcasting was failed")
}
//결과 : Downcasting was failed

as?를 사용하면 성공할 시 Optional값을 반환하고, 실패할 시 nil을 반환한다.

 

class Parent { }
class Child : Parent { }

let parent : Parent = Parent()
let child : Child = Child()

if let downcasting = parent as! Child {
    print("Downcasting was successful")
}
else{
    print("Downcasting was failed")
}
//결과 : error

as!를 사용하면 성공할 시 강제언래핑한 값을 반환하고, 실패할 시 런타임 오류가 생긴다.

그래서 위의 코드는 에러가 떴다.

 

 

2. 타입 검사(is)

is 연산자를 사용하여 객체의 데이터 타입을 검사한다.

class Parent { }
class Child : Parent { }

let parent : Parent = Parent()
let child : Child = Child()

if parent is Child{
    print("the data type of parent is Child")
}
else if parent is Parent {
    print("the data type of parent is Parent")
}
else{
    print("Parent and Child are not the data type of parent")
}
// 결과 : the data type of parent is Parent

parent is Parent는 객체 parent의 데이터 타입이 Parent인가를 뜻한다.

parent가 Parent 타입의 변수이면 true를 반환해서 if문을 실행하고, 아니면 false를 반환해서 else if나 else 코드를 실행한다.

 

 

 

 

Any

 

모든 자료형을 담을 수 있는 것이다.

var hello : Any = "hello"
print(hello, type(of:hello))
hello  = 1.5
print(hello, type(of:hello))
hello  = 100
print(hello, type(of:hello))
//결과 : hello String
//1.5 Double
//100 Int

 

 

 

 

AnyObject

 

모든 클래스 자료형을 담을 수 있는 것이다.

class A{}
var a = A()
var hello : AnyObject = a
print(type(of:hello))
//결과 : A

* Int, String, Bool, Float, Double은 모두 구조체이다.
그러므로 AnyObject형 변수에는 위의 자료형 값을 대입할 수 없다.

 

 

 

 

범위 연산자

 

1...5 : 1 2 3 4 5

1..<5 : 1 2 3 4

...3 : 처음부터 ~ 3까지

3... : 3부터 끝까지

..<3 : 처음부터 ~ 3빼고

 

 

 

 

삼항연산자

 

1 < 3 ? "yes" : "no"

1보다 3이 크면 yes를 반환, 1보다 3이 작으면 no를 반환

 

 

 

 

nil합병연산자(Nil-Coalescing Operator)

 

사용 연산자 : ??

let defaultValue = 10
var num : Int?
// num에 nil이 들어있으면(값이 없으면) defaultValue를 반환한다.
// num에 값이 있으면 언래핑한 값을 리턴한다.
print(num ?? defaultValue)
//결과 : 10

 

 

 

 

 

Swift 3에서 없어진 것

 

for var n = 0; n < 10; n += 1 대신  -->  for n in 0..<10 써야함

n++ 대신   -->   n+=1 or n=n+1 써야함

 

 

 

 

제어문

 

for-in문

for i in 1...10 {
}
for _ in 1...10{ // 이것도 가능
}

 

while

while 1 < 3{ // 무한 루프
}

 

repeat-while문

(do while문과 같음)

repeat{}안에 들어있는 코드를 처음에 무조건 실행하고 다음에 while 조건에 따라 반복하는 제어문

repeat { // == do

}while 1 < 3 // == while

 

break

while 0 < 1 {
    print("무한 루프~~")
    break // while문 탈출!
}

 

continue

(건너뛰는거라고 생각하면 됨)

for i in 1...5 {
	if i == 2 {
    	continue
    }
    print(i, terminator:"")
}
//결과 : 1345

2만 건너뛰고 출력한다.

 

if문

if 1 < 2 && 2 < 3 {
}
//같음
if 1 < 2, 2 < 3 {
}

주의 Swift에서 if문은 꼭 {}를 써줘야 한다. 코드 한 줄이라고 대괄호 안써주면 error가 난다.

 

if-else문

if 조건 {
}
else if 조건 {
}
else if 조건 {
}
else {
}

 

 

 

 

dictionary

 

key와 value로 여러 개의 데이터를 저장하는 것

ex)

// dictionary
let numberOfStudent : [String : Int] = ["Ann" : 001, "Jane" : 002, "Tom" : 003]
for (name, studentNumber) in numberOfStudent { 
	print("\(name)'s number is \(studentNumber).") 
}
//결과 : Jane's number is 2.
//Ann's number is 1.
//Tom's number is 3.

 

 

 

 

 

 

출처 : iOS프로그래밍기초(21-2학기)한성현교수 강의 내용 변형 및 요약

반응형

'프로그래밍 > Swift' 카테고리의 다른 글

Swift 문법 정리 3  (0) 2021.09.26
Swift 실습 3  (0) 2021.09.25
Swift실습2  (0) 2021.09.17
Swift의 변수와 상수, 튜플 - 실습  (0) 2021.09.16
Swift의 변수와 상수, 튜플  (0) 2021.09.12
Comments