/* Optionals */
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// nil
var serverResponseCode: Int? = 404
serverResponseCode = nil
var surveyAnswer: String?
// If Statements ans Forced Unwrapping
if convertedNumber != nil {
print("convertedNumber contains some integer value")
}
if convertedNumber != nil {
print("convertedNumber has an inter value of \(convertedNumber!)")
}
// Optional Binding
if let actualNumber = Int(possibleNumber) {
print("The string \"\(possibleNumber)\" has an inter value of \(actualNumber)")
} else {
print("The string \"\(possibleNumber)\" could not be converted to an inteager")
}
if let firstNumber = Int("4"), let secondNumber = Int("42"),
firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
// Impicityly Unwrapped Optionals
let possibleString: String? = "An optional string"
let forcedString: String = possibleString!
let assumedString: String! = "An Implicitly unwrapped optional string"
let implicitString: String = assumedString
if assumedString != nil {
print(assumedString!)
}
if let definiteString = assumedString {
print(definiteString)
}
// Early Exit (Control Flow)
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location)")
}
greet(person: ["name": "John"])
greet(person: ["name": "Jane", "location": "Cupertino"])