This is going to be a quick post on one of the things that Swift does a little differently from other modern languages you may be familiar with.
In C# land, we are used to two distinct classes of variables. The first class are value types like int and double that have a default value and cannot be null. On the other side you have your proper reference type objects which are nullable. Most of the types you are going to work with in C# are going to be reference types. Languages like Ruby go even further and make all variables reference types.
Swift takes things in the other direction. All variables are value types by default. They have to contain a value and cannot be assigned null. The do allow you to alternatively declare variables as optional(i.e. nullable)
So, you’re probably thinking, “Hey I can declare an int as nullable in C# with a ‘?’ after the type too.” Well, not really. In C# you are pretty much using a connivence operator that wraps the value type in a Nullable reference type. Plus, in Swift, this is also the case:
It can be kind of handy to know that, when you get passed in a reference to an object, you can force the caller to make sure that they are sending you a real parameter. I would love for a non-nullable in C#. It can get real old writing if(foo!=null){}.
If you are familiar with Nullable in C#, you know how you always have to test HasValue before you can access the value contained within. You have a similar situation with Swift where you have to force the unwrapping of optionals into non-optionals before you can use them.
Of course, if optional was nil, you’d get a runtime error. Alternatively you can do this instead:
This version of the code handles the unwrapping gracefully. It will just return nil from the expression; which is why myNotes also has to be an optional type. Though, what you really want to do here is use optional chaining.
There’s one more part to this whole optional thing, and that’s implicitly unwrapped optionals. Basically they’re optionals that you know have a value, and you don’t want to bother with the whole “explicit unwrapping every time you want to access your variable” thing.
You can treat the variable as non-optional, but can still assign it a nil value. It will still throw an error if nil just like when you explicitly unwrap an optional, but at least it looks prettier while it goes down in flames. I kind of wish that implicitly unwrapped optionals where the default. That makes the most sense to me, but that just may be my C# developer showing since they resemble C# reference types the most.
Build awesome things for fun.
Check out our current openings for your chance to make awesome things with creative, curious people.
You Might Also Like