8 ms·
The more I use swift, the more I've grown to appreciate the concept of Optionals and how the compiler enforces it's usage. I have found that my swift code is mo
by seanalltogether 10y ago
The more I use swift, the more I've grown to appreciate the concept of Optionals and how the compiler enforces it's usage. I have found that my swift code is more robust and explicit than my ObjC or Android java code is, as well as the team members around me.
- burntcookie90 10y agomake sure you check out kotlin then, for Android
- wyager 10y ago> the more I've grown to appreciate the concept of Optionals You may also enjoy a language that supports the generalization of Optionals, which are Algebraic Data Types (ADTs). Optionals are a single, limited application of ADTs. Optionals allow you to shift null pointers (and null pointer exceptions) to the type level. So instead of having to worry about a function returning null, you just deal with Optionals whenever a function returns one. There's another ADT, usually called "Either" or "Result", that allows you to shift exceptions to the type level. You can see from the type of the function what kind of exception it might return, and you deal with exceptions like any other value instead of via a special exception handling mechanism.
- austinz 10y agoSwift supports ADTs and implements its Optional type as an ADT.
- wyager 10y ago> Swift supports ADTs True, but perhaps not practically relevant. The pattern matching in Swift isn't much better than what you would get with a tagged C union, which is why no one really uses it very heavily. The Optional type in Swift gets a lot of special compiler support, which is indicative of the fact that the broader language isn't very friendly towards using ADTs to structure data. But you're right, I should have clarified in my comment that Swift does have a basic degree of support for ADTs.
- austinz 10y ago> The pattern matching in Swift isn't much better than what you would get with a tagged C union In what way? Pattern matching in Swift is quite powerful; definitely better than C's switch statement. This blog post is a good overview of its capabilities. https://appventure.me/2015/08/20/swift-pattern-matching-in-detail/ https://appventure.me/2015/08/20/swift-pattern-matching-in-d...
- xenadu02 10y agoIn what way is Swift pattern matching not "much better than what you would get with a tagged C union"? enum in Swift has pattern matching support, can have properties, adopt protocols, etc. I would disagree with your assessment that "nobody uses them".
- eridius 10y agoI don't know what kind of Swift code you're writing, but you're very, very wrong when you say "no one really uses it heavily". Pattern matching is in fact quite powerful and is used heavily in any codebase that isn't simply a straight porting of Obj-C idioms. > The Optional type in Swift gets a lot of special compiler support Only the ?. optional chaining operator (and technically the ! postfix operator too, though that could have been implemented in the standard library instead of being special syntax and in fact I'm not really sure why it isn't just a stdlib operator). And probably some logic in the switch exhaustiveness checker so it knows nil is the same as Optional.none. Everything else (including the actual pattern matching against the "nil" keyword) is done in a way that can be used by any type, not just Optionals (nil for pattern matching specifically evaluates to a stdlib type called _OptionalNilComparisonType which implements the ~= operator so it can be compared against any Optional in a switch, and you could do the same for other ADTs too, assuming they have a reasonable definition for nil).
- ridiculous_fish 10y agoOne of the things that makes Optional so pleasant in Swift is the syntax support. This includes optional-chaining, if-let and guard-let unwrapping, and some convenient operators. For example, in Haskell, by default you can't compare an Optional with the value it wraps: `5 == Just 5` fails. But in Swift this works like you would want. All that is to say that Options in Swift are a bit nicer than what you could get with pure ADTs. It's a similar story for Swift's syntax-level error handling vs type-level monadic error handling. (The downside of course is that the compiler has to be specially taught about these - but maybe you want that anyways, e.g. for Rust's null-pointer optimization.)
- wyager 10y ago> This includes optional-chaining, Haskell has bind (>>=) and do-syntax, rust has `and_then`. This is pretty standard with any ADT-supporting language. > if-let Most languages with ADT support have good pattern matching that subsumes if-let syntax and allows you to do other things as well. Swift's pattern matching, such as it is, is a bit of a mess. > guard-let unwrapping Haskell has `guard` and `MonadFail`, which address the use cases for this in a more principled way. `guard` for boolean matching (like equality) and `MonadFail` for structural matching (like pattern matching on a constructor). Rust has (?) and `try`, which are syntactic sugar around a simple match/return statement that addresses most use cases of guard-let. Obviously there are going to be small differences between this implementations, but Swift doesn't really excel here. > `5 == Just 5` fails. As it probably should. Supporting such implicit casting could lead to some obvious confusion and buggy behavior. Ideally, the fact that "a == b" typechecks should indicate that "a" and "b" are of the same type. In Haskell, you would just do `Just 5 == x` if you want to check that something is, in fact, `Just 5`. If that really wasted a lot of space somehow, you can define something like `x ==: y = Just x == y`.
- comex 10y agoRust copied 'if let' from Swift (~2 years ago) despite having decent pattern matching; community consensus today is that it's highly worthwhile as a feature. There have also been proposals to add 'guard let'. So, while I don't have enough Swift experience to judge its ADT support overall, I wouldn't cite those features as evidence that it's wanting. They might not be as natural in traditional FP languages like Haskell, but they seem to fit pretty well in the stylistic niche Rust and Swift (among other languages) have carved out. edit: FWIW, there's some overlap between '?' and 'guard let', but not that much. Using hypothetical Rust syntax, they'd overlap in this case: guard let Some(x) = foo else { return Err(GettingFoo); } better expressed as let x = foo.ok_or(GettingFoo)?; …but if you want to return something other than a Result, or the ADT being matched on is something custom rather than Option/Result, there's no good way to make '?' do the job.
- kazagistar 10y agoSwift does fully support ADTs, and can easily model result types, they just chose to have catchable exceptions as well.
- hardwaresofton 10y agoWhile I'm sure you're aware, Java 1.8 does have Optional support (https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html https://docs.oracle.com/javase/8/docs/api/java/util/Optional...). Once Jack is completed (https://developer.android.com/guide/platform/j8-jack.html https://developer.android.com/guide/platform/j8-jack.html) I assume you'll be able to use it too. Of course, you can also just use a library (like Guava) that makes Optionals available (and somewhat close to the spec so you can phase it out in the future if need be). Some quick googling found me: http://fernandocejas.com/2016/02/20/how-to-use-optional-on-android-and-java/ http://fernandocejas.com/2016/02/20/how-to-use-optional-on-a... ... One thing I've found is that once you start using Optionals, they tend to infect (I don't mean this in a bad way) the rest of the code. You start to want Optionals everywhere, and start writing maps/orElses everywhere, which I personally love. The error-handling paradigm changes a little bit (to errors-as-values, which I personally appreciate as well), but some are turned off by having optionals everywhere.
- wfleming 10y agoMaybe I'm wrong about how it works, but I feel that Optionals in Java are a bolt-on solution that only solves half the problem that the same concept solves in Swift (or Haskell, or Rust, etc.) An Optional in Java is just another value, and nothing in practice stops that from being null. I.e. a method that returns an Optional can still return an actual null if poorly implemented. So the major benefit Optionals give you in Java is a typed declaration that the method may return an "empty" value, which is certainly helpful for knowing what cases your client code needs to handle, but it does not guarantee that the method will never return null. It reduces the probability of unhandled null pointers, but it does not eliminate them. On the other hand, Swift & co. guarantee at compile time that a function which says it returns an Optional will always return an an Optional, never a null, and, better still, if a function says it returns some non-optional value, it still is guaranteed to never return null. It's great that Java is pushing for this style of code, but I'm afraid without compile-time guarantees of return values it will always feel less powerful there.
- lern_too_spel 10y ago
- edblarney 10y agoThis is a big thing for Swift - the 'optional' paradigm is totally unavoidable, and heavily affects the code as usage is fairly pervasive. Not having used them much in the past, I rather don't like them, but I'm aware of the fact they could simply take getting used to. Anyone chime in on whether or not Optionals are really the 'future of good syntax'? Or they are quirk? Or good in some cases, not for others?
- interpol_p 10y agoOptionals being clumsy means you start to eliminate them as you write more Swift. It becomes a carefully considered decision to use an optional in your interface. And the compiler keeps you in line. I love the compile-time optional support now and severely miss it when using languages that don't have the feature. They are brilliant when you are working with all-Swift code or Objective-C code that has been decorated with nullability keywords. However optionals become a burden when you are working with old Objective-C code that has not been annotated.
- masklinn 10y agoOptionals should be used sparingly in de-novo Swift code, as the corresponding features (Option/Maybe types) are in other languages (Haskell, Elm, OCaml, Rust, …): only make something an Optional if, well, it's actually optional. Optionals have lots of syntactic sugar because Swift has to deal with reams of native and objective-c code which is ubiquitously nullable, dealing with that without the syntactic sugar would be nothing short of horrendous. This is also an issue with ported/converted API (which is most of them at this point) as the underlying system tends to leverage nullability extensively (it's a very common Obj-C pattern as nil is a message sink), which is usually left shining through by simple conversion rather than wrap every historical API in a converted Swift version.
- zem 10y agothe nearest analogue to swift in the android ecosystem is kotlin - give it a look if you haven't.
- deleted 10y ago[deleted]
- 35bge57dtjku 10y agoPeople have known about Optionals being better for decades.