Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1693
深忆病人
深忆病人 2020-11-22 07:30

Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a

10条回答
  •  情话喂你
    2020-11-22 07:45

    I think Optional is a bad name for this construct that confuses a lot of beginners.

    Other languages (Kotlin and C# for example) use the term Nullable, and it makes it a lot easier to understand this.

    Nullable means you can assign a null value to a variable of this type. So if it's Nullable, you can assign nulls to it, if it's just SomeClassType, you can't. That's just how Swift works.

    Why use them? Well, sometimes you need to have nulls, that's why. For example, when you know that you want to have a field in a class, but you can't assign it to anything when you are creating an instance of that class, but you will later on. I won't give examples, because people have already provided them on here. I'm just writing this up to give my 2 cents.

    Btw, I suggest you look at how this works in other languages, like Kotlin and C#.

    Here's a link explaining this feature in Kotlin: https://kotlinlang.org/docs/reference/null-safety.html

    Other languages, like Java and Scala do have Optionals, but they work differently from Optionals in Swift, because Java and Scala's types are all nullable by default.

    All in all, I think that this feature should have been named Nullable in Swift, and not Optional...

提交回复
热议问题