Optional chaining is one of the great, useful features of Swift. It can be used “for querying and calling properties, methods, and subscripts on an optional that might currently be nil,” to quote Apple's "The Swift Programming Language.” However, often it is necessary to call a function, subscript, or initializer conditionally based on if one or more parameters are nil. The proposed solution is to allow a question mark (?) to be placed after an optional value wished to be used as a parameter. Then, the function, initializer, or subscript will be called if and only if the parameter's value is not nil. If it has a return type, it will return an optional, which will be nil if the parameter is nil.
Old way (with seemingly unnecessary if statement considering the flexibility provided by optional chaining):
var arr = ["apples", "oranges", "pears", "bananas"]
let index: Int? = 2
var removedElement: String?
if let index = index {
removedElement = arr.removeAtIndex(index) //sets removedElement to "pears"
}
Using this proposal:
var arr = ["apples", "oranges", "pears", "bananas"]
let index: Int? = 2
var removedElement: String?
removedElement = arr.removeAtIndex(index?) //sets removedElement to “pears"
Another similar example:
Old way:
var arr = ["apples", "oranges", "pears", "bananas"]
let index: Int? = nil
var removedElement: String?
if let index = index {
removedElement = arr.removeAtIndex(index) //never called
}
Using this proposal:
var arr = ["apples", "oranges", "pears", "bananas"]
let index: Int? = nil
var removedElement: String?
removedElement = arr.removeAtIndex(index?) //removeAtIndex is never called, and removedElement is set to nil
What does everyone think of this proposal? It is additive so it will not break any existing code, and in the future it will provide conciseness and clarity since the syntax is similar to the existing optional chaining syntax.
View the full proposal on GitHub here: https://github.com/liam923/swift-evolution/blob/master/proposals/NNNN-extend-optional-chaining-to-function-initializer-and-subscript-parameters.md
Liam