옵셔널 in 스위프트(Optional values in Swift)
필그램
·2017. 3. 22. 07:48
스위프트의 가장 다른 코드중의 하나는 Optional values 이다.
일반적인 코드는 아래와 같다.
var str2:String = "Example"
str2.replacingOccurrences(of: "Ex", with: "S")
결과
"Example"
"Sample"
var str2:String? = "Example"
str2?.replacingOccurrences(of: "Ex", with: "S")
결과 "Example"
"Sample"
여기서 ?는 nil 또는 null이 될수 있다는 것이다.
var str3:String? = nil
str3?.replacingOccurrences(of: "Ex", with: "S")
결과 nil
nil
nil이더라도 결과 값이 에러가 나지 않는다는 것이다. (ignored after ? mark)
그러나 ! 를 사용함으로써, 다음은 nil값이 아닐것이라는 내용의 코드이다.
var str4:String! = "Example 4"
str4!.replacingOccurrences(of: "Ex", with: "S")
// implicitly unwrapped optional. So, we use an exclamation point to declare that.
다음과 같이 변형하면 에러가 나온다.
var str5:String! = nil
str5!.replacingOccurrences(of: "Ex", with: "S")
! 는 nil값이 안나올 꺼라는 가정에서 쓰는것이기 때문에 에러를 발생시킨다.
다음과 같이 ? 다음에 ! 를 넣는것은 가능하다.
var str5:String? = "Example 5"
str5!.replacingOccurrences(of: "Ex", with: "S")