Optionals

The last few posts have been a summary and consolidation of what I know about Swift. It was a cathartic process, talking through what I know about it at this point and reminding myself of why I am learning it too! This blog will from now on detail my immediate thoughts and reflections about what I learn with Swift. This one starts from page 52 of 'Learn to Code in Swift 4' by Kevin McNeish. The first few chapters have been an introduction to Swift, how to navigate the Ebook, a bit about Xcode and about objects/classes. This feels like a good point to begin my 'live' reflections: Optionals!



Optionals allow you to specify that a variable or constant may return 'nil' (nothing). Now what exactly that means I'm not sure about, at this point. They seem to be an important element of Swift so I need to get my head around them. Apparently they let you be more precise - telling the code when it's OK for a value to be empty, and when not. So, if an unexpected 'nil' is returned then the program could crash! Right, so these Optionals are a way of planning in situations where 'nil'/nothing could be returned.

var middleName: String?

This is an example of an optional. In this case, the variable 'MiddleName' has been declared as an optional string. The question mark is used to show this. So now we know that this string could be nil' at the moment nil is returned in the sidebar results. Makes sense! Also, something that's made clear in this chapter, and in the Apple Swift book, is that you cannot put nil as the value for constants or variables that are non-optionals. This could cause the program to crash!


To access the optional value, it needs to be 'unwrapped'. Here is an example:

var firstName: String = "Bernard"

var middleName: String? = "Cornelius"

var firstAndMiddleNames: String

firstAndMiddleNames = firstName + " " + middleName



A compile-time error appears! I'm guessing that this is because the optional was not 'unwrapped'. Yes it is! As the 'middleName' variable may be nil, it needs to be unwrapped...still not getting the point yet. Anyway, there are two types of unwrapping: forced and optional binding. 

Forced unwrapping involves using an ! after the optional basically. This works fine for the above example but if my middleName variable did contain nil, then there would be a runtime error. So the only time to use forced unwrapping is when you are certain that the optional does contain a value.


The other way, Optional Binding, is considered safer:

if let middle = middleName {
    firstAndMiddleNames = firstName + " " + middle
    print("Middle name not nil")
    
} else {
    firstAndMiddleNames = firstName
    print ("Middle name is nil")
}


In the above example, an if condition is checked to see if middleName contains a string. As it is true, then the first print statement is printed. 

'Implicitly Unwrapped Optionals' do not need to be unwrapped - so if you know an object will never be nil, it's useful to have implicitly unwrapped optionals (the ! symbol is used instead of ? upon declaration). 

'Optional Chaining' includes 'nested' properties - something I'm vaguely familiar through nested functions. 


Example:

class MemberEntity {
    
    var location: LocationEntity?
    var firstName: String = ""
    var lastName: String = ""
    
    init() {
        
    }
}

class LocationEntity {
    
    var locationName: String = "Cupertino"
    var locationDescription: String = "Apple's Home"
    var locationId: Int32 = 1
}


OK, to be honest I've had a look through about how this works in practice in the Ebook but I don't get it. It's something I will have to come back to at some point! Perhaps reading up on Optional Chaining with an easier example could do the trick!

The other thing this chapter mentions is the 'nil Coalescing Operator'. This unwraps an optional (a??b syntax) if it contains a value or if not, will return a default value. 


Here's a summary for this chapter:


  • Optionals also you to specify that a var/let can contain a value or nil. 
  • A question mark is used to show that it is optional. 
  • If no initial value is given then it is assumed that it is nil (only optionals can be used - program will crash otherwise). 
  • You have to 'unwrap' the optional: by forced unwrapping (use of !), optional binding (if/let statement), making it implicitly unwrapped (! instead of ? to start with), or optional chaining (...)


So, I think I understand Optionals a bit better than before. Optional Chaining is still mind boggling at the moment. Some progress has been made for sure but like I've said, I need to get the Optional Chaining aspect of it mastered. That is something I will revisit and look at other sources for as it was simply too confusing in this chapter. Looking ahead in the Ebook (pages 69 to 82), the next part is all about Calling Methods, so that will be the focus next time. 






Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)