하루를살자

Swift - Optionals 본문

Swift

Swift - Optionals

Kai1996 2021. 12. 21. 01:00

Usage

- The Optional is used to declare a variable but don't want to set a default value

- It is used when using nil to represent an unset state 

- when using a variable to reference data that can actually be nil 

 

Two ways to use Optionals 

1. Implicitly unwrapped optional

2. Optional


// Implicitly Unwrapped optionals 
// It can contain nil 
// Xcode doesn't alert the user 
// It doesn't need to be unwrapped

var a:String! = nill 


//Optional
//It can contain nill 
//Xcode warns the user 
//Need to unwrap the variable to get value 
var b:String? = nill 

// Optional Binding 

if let a = b {
    var x = a + 1
    print(x)
}

The Optional Binding checks whether the variable b is nil or not, and if it isn't, it assigns its value into Constant "a". So when using inside of If loop, it is not necessary to unwrap variable "a" using "!".

 

 

'Swift' 카테고리의 다른 글

Swift 고차함수  (0) 2022.02.05
Swift - Collection Types  (0) 2022.01.01
Swift - Enum  (0) 2021.12.31
SwiftUI Architecture - MVVM (Model, View, and ViewModel)  (0) 2021.12.20
Swift Basics - Playground(Xcode), Data type, Function  (0) 2021.12.17
Comments