Subscripts can now declare default arguments
About 2 min
Subscripts can now declare default arguments êŽë š
HACKING WITH SWIFT
What's new in Swift?
Subscripts can now declare default arguments | Changes in Swift 5.2
Subscripts can now declare default arguments
Available from Swift 5.2
When adding custom subscripts to a type, you can now use default arguments for any of the parameters. For example, if we had a PoliceForce
struct with a custom subscript to read officers from the force, we could add a default
parameter to send back if someone tries to read an index outside of the arrayâs bounds:
struct PoliceForce {
var officers: [String]
subscript(index: Int, default default: String = "Unknown") -> String {
if index >= 0 && index < officers.count {
return officers[index]
} else {
return `default`
}
}
}
let force = PoliceForce(officers: ["Amy", "Jake", "Rosa", "Terry"])
print(force[0])
print(force[5])
That will print âAmyâ then âUnknownâ, with the latter being caused because there is no officer at index 5. Note that you do need to write your parameter labels twice if you want them to be used, because subscripts donât use parameter labels otherwise.
So, because I use default default
in my subscript, I can use a custom value like this:
print(force[-1, default: "The Vulture"])
Other Changes in Swift 5.2
Key path expressions as functions | Changes in Swift 5.2
Key path expressions as functions
Callable values of user-defined nominal types | Changes in Swift 5.2
Callable values of user-defined nominal types
Lazy filtering order is now reversed | Changes in Swift 5.2
Lazy filtering order is now reversed
New and improved diagnostics | Changes in Swift 5.2
New and improved diagnostics