7

!rant
Loving the the fact that constructors in Swift (initializers) can fail (returning null/nil) and be async.

In C# there is no other way than using static methods instead.

Comments
  • 1
    Been a long time since I coded in swift now I use typescript, I miss writing mobile apps in native languages :\
  • 1
    Been learning swift recently and I've been liking it a lot. I hate the storyboard UI workflow though, I'm glad they made Swift UI.
  • 1
    @ars1 yeah I don’t recommend learning the old UI stuff (UIKit).
    You can do almost everything with SwiftUI now.
  • 1
    Why, why, why would you be doing I/O in a constructor?
  • 0
    Yes, why would a constructor have a side effect so unstable that it is allowed to fail?
    Cannot you pass the failable component as a parameter and avoid the constructor to fail?
    In my last 20 years I never ever needed a constructor to fail.
  • 1
    @spongessuck is this a troll question? Do you really think that async == I/O?
  • 0
    @Feibrix why should I try to avoid the constructor to fail? If I did, I would allow the constructed object to be in an invalid state.
    One of the simplest cases for failable constructors is the constructor of an enum case that takes the enum’s backed int value as a parameter. If there is no enum case for that int, what enum value should be constructed? Well obviously it should fail and that’s how swift enums work.
    This logic can be applied to structs and classes, too.

    You probably never needed a failable constructor in your 20 years because everytime that you actually needed one, you used a static method instead. You mistakingly and subconsciously interpreted the fact that c# doesn’t support it as something that shouldn’t be done or is not needed. A common fallacy.
  • 0
    @Feibrix and regarding your statement about side effect: I don’t know why you assume that failability has something to do with side effects but it doesn’t.
Add Comment