This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3605-202-programming-in-a-swift-style
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3605-202-programming-in-a-swift-style
I’ve learned that optionals are a concept which doesn’t exist in C or Objective-C. They allow functions that are not always able to return a meaningful value (for example, in the case of incorrect input), to return either a value encapsulated in an optional, or in nil. In C and Objective-C, we can already return nil from a function that normally returns an object, but we do not have this option for functions that should return a base type, such as int, float, or double. I wrote remarks:
let a = "512"
let b = Int(a)
print(b) // Optional(512)
The Int function in this case returns an optional parameter containing the value of int 512, as expected. But what happens if we try to convert something like “Hello” instead? In this case, the function returns nil, as described above:
let a = "Hello"
let b = Int(a)
print(b) // nil
As you may already know, in Objective-C, if you call a method with a null pointer, nothing happens. No compilation errors, no runtime errors, nothing. This is a well-known source of errors, unexpected behavior and general frustration: the lack of feedback means that developers are forced to independently determine the source of these errors.
With Swift, you don’t have worry about this:
var x = Int("555")
print(x.successor()) // error
The compiler itself will generate an error, since x is now optional and could potentially be nil. Before using the optional value, you need to expand it as follows:
var x = Int(“555”)
if x != nil {
print(x!.successor()) // 556
}
Alternately, we can use optional binding:
var x = Int("555")
if var y = x {
y += 445
print(y) // 1000
}
resourse: essayshark