Posts

Showing posts from September, 2018

Let’s understand what is optional in Swift and how to use !!

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all. The example below shows how to declare optional variables.     1.    var optionalVariable1: String?     2.    var optionalVariable2: Int?     3.    func swapInt(int1: Int?, int2: Int?) // as a function argument     4.    func doSomething() -> String? // function return value as optional So basically you use optional when you think some variable’s value or function’s return value can be nil in some conditions. You can check the optional variable against nil before accessing, like below If optionalVariable1 != nil {      // your code } The example below uses the initializer to try to convert a String into an Int:     1.    let possibleNumber = "123"     2.    let convertedNumber = Int(possibleNumber)     3.    // convertedNumber is inferred to b