The use of optional in swift

In c/c++, 0 and null are often used to represent no value, and optional was developed in swift to replace this risky practice

Both ? and ! can be used to define optional variables

! Can also be used to force unpacking, but use! The defined optional means that there must be a value, use! That is to omit those unnecessary checks, but there is a risk

var x: Int? = 8

1. Poor usage

x!+ 2

2, the relatively poor processing method

if x != nill {

  x = x! + 1

}

3. Recommended handling method

var x: Int? = 8

if let myNumber = x {

  myNumber + 1

}

highScore = loadedScore != nil ? loadedScore! : 0

highSrore = loadedScore ?? 0


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325542581&siteId=291194637