3 ms·
Please - tell me that's not something one might actually encounter in practice (and yes I know, it'll feel clever to respond with up votes and down votes but pl
by yodon 9y ago
Please - tell me that's not something one might actually encounter in practice (and yes I know, it'll feel clever to respond with up votes and down votes but please don't as I'll not have any idea what they mean: good point! Or stupid comment! Or you would totally see this! Or you wouldn't! And for the last two which vote is which?)
- programmarchy 9y agoYou would totally see this in the code I've been writing. I've been taking advantage of enums with associated values for things like state machines. Usually, you'll see associated values like this in a switch statement, but if you need to handle a specific case, then you'll see the `if case`.
- Koshkin 9y agoYou'll be surprised how soon after you start writing Swift you'll be doing this yourself - and enjoy it. Exploring new features and learning new ways of doing things is fun. Otherwise, what's the point in learning a new language? Seeing more of the same?
- pivo 9y agoNot 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.