Optionals

Optionals

var name = "Matt Galloway"
var age = 30
var occupation = "Software Developer & Author"

var errorCode: Int?
errorCode = 100
errorCode = nil

var result: Int? = 30
// print(result) // warning
//print(result + 1) // error: Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
print(result ?? 0)
print(result!)
print(result as Any)

// IF-LET BINDING (AND FORCED UNWRAPPING)
var authorName: String? = "Matt Galloway"
var authorAge: Int? = 30

var unwrappedAuthorName = authorName!
print("Author is (unwrappedAuthorName)")

authorName = nil
//print("Author is (authorName!)")

if authorName != nil {
print("Author is (authorName!)")
} else {
print("No author.")
}

if let unwrappedAuthorName = authorName {
print("Author is (unwrappedAuthorName)")
} else {
print("No author.")
}

if let authorName = authorName {
print("Author is (authorName)")
} else {
print("No author.")
}

if let authorName = authorName, let authorAge = authorAge {
print("The author is (authorName) who is (authorAge) years old.")
} else {
print("No author or no age.")
}

if let authorName = authorName, let authorAge = authorAge, authorAge >= 40 {
print("The author is (authorName) who is (authorAge) years old.")
} else {
print("No author or no age or age less than 40.")
}

// GUARD
func calculateNumberOfSides(shape: String) -> Int? {
switch shape {
case "Triangle":
return 3
case "Square":
return 4
case "Rectangle":
return 4
case "Pentagon":
return 5
case "Hexagon":
return 6
default:
return nil
}
}

func maybePrintSides(shape: String) {
guard let sides = calculateNumberOfSides(shape: shape) else {
print("I don't know the number of sides for (shape).")
return
}

print("A (shape) has (sides) sides.")
}

// NIL COALESCING
var optionalInt: Int? = 10
var mustHaveResult = optionalInt ?? 0

optionalInt = nil
mustHaveResult = optionalInt ?? 0

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容