importCocoa// ## optionals/*
Optionals are like a box that may or may not have something inside.
var number: Int? = nil
var name: String? = "hello world"
*/// 3 ways to unwrap optionals// 1) if letvaropposites=["Mario":"Wario","Luigi":"Waluigi"]ifletmarioOpposite=opposites["Mario"]{print("Mario's opposite is \(marioOpposite)")}varname:String?="hello world"ifletname=name{print("name is \(name)")}// 2). guard let ... elsefuncprintSquare(ofnumber:Int?){guardletnumber=numberelse{print("Missing input")return}print("\(number) x \(number) is \(number*number)")}printSquare(of:4)// a more general version of guard is:// guard someArray.isEmpty else { return }.// 3) ??letnew=opposites["Peach"]??"N/A"letinput=""letnumber=Int(input)??0print(number)// chaining/*
Optional chains can go as long as you want, and as soon as any part sends
back nil the rest of the line of code is ignored and sends back nil.
*/// example 1letnames=[String]()letchosen=names.randomElement()?.uppercased()??"No one"print("Next in line: \(chosen)")// example 2structBook{lettitle:Stringletauthor:String?}varbook:Book?=nilletauthor=book?.author?.first?.uppercased()??"A"print(author)// ## use `try?`/*
If the function ran without throwing any errors then the optional will
contain the return value, but if any error was thrown the function will
return nil.
*/enumUserError:Error{casebadID,networkFailed}funcgetUser(id:Int)throws->String{throwUserError.networkFailed}ifletuser=try?getUser(id:23){print("User: \(user)")}// orletuser=(try?getUser(id:23))??"Anonymous"// ## checkpoint/*
write a function that accepts an optional array of integers, and returns one randomly. If the array is missing or empty, return a random number in the range 1 through 100.
*/funcrandomPick(nums:[Int]?)->Int{returnnums?.randomElement()??Int.random(in:1...100)}print(randomPick(nums:[]))
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)