3 ms·
Not only is this not unusual it is completely normal and even banal when using Swift enumerations with associated values. It might look strange to someone who d
by pivo 9y ago
Not only is this not unusual it is completely normal and even banal when using Swift enumerations with associated values. It might look strange to someone who doesn't know the language, but a few minutes reading about Swift's enumerations will clarify what this code is doing and it will become totally mundane.
struct Person {
var name: String
}
enum Result<T> {
case success(T)
case error(NSError)
}
func printName(personResult: Result<Person>) {
if case .success(let person) = personResult {
print(person.name)
}
}
In the example above, Result is an enumeration that can be either success or error. If it's success it has an associated value that is the result of whatever operation was successful. If it's error the associated value contains the error information.
In the case of printName() the success case contains a Person value. The if-case is simply saying that if the enumeration represents the success case then extract the associated Person value from the enumeration. The "let person" means make person a constant because you're not intending to modify it. If you wanted to modify it you'd use "var person" instead.
Hopefully this is pretty clear even to people not familiar with Swift style enumerations.
- megaman22 9y agoAh, it's an ugly, verbose syntax for pattern matching. Got it :-)
- pivo 9y agoWell, it's very similar to Scala's pattern matching. Not as elegant as Erlang or Haskell's. Objective-C, which is what Swift is being compared to here, doesn't have pattern matching. An attempt to write something similar in Objective-C would be much more verbose, unsafe and almost certainly uglier.
- Grustaf 9y agoYou may find it ugly, that's subjective - I personally find it weird and unintuitive. But you can't really say it's verbose, there is no redundant information there.