swift Optional

//optional

let fName:String = "hi"
let mName:String? = nil //"Hello"
let lName:String = "Wel"

//this is not good method
if mName != nil {
print("\(fName) \(mName!) \(lName)")
}
else{
print("\(fName) \(lName)")
}

//good method (unwrapping)
if let middleName = mName {
print("\(fName) \(middleName) \(lName)")
}
else{
print("\(fName) \(lName)")
}

//Optional chaining
class School{
var director:Person?

}

class Person{
var name:String = ""
init(name:String) {
self.name = name
}

}

let school = School();
let person = Person(name: "Ali")
school.director = person
if let name = school.director?.name {
print("director name \(name)")
}
else{
print("no director")
}
Previous
Next Post »