Tonight’s meeting will focus on continuing the development of the WeatherWear Web Service and the Swift app to consume the Web Service.
Notes on Swift String Interpolation Issue with Optional variables:
String Interpolation in Swift: the term “string interpolation” refers to creating a character string that pulls values out of one or more variables and combines those values with other characters to form a string. The entire expression is enclosed in double quotes and each variable within the string is preceded by a backslash and enclosed in parentheses. Example “Hello \(name)” will print “Hello Gandalf” if Gandalf is the value in the variable name.
Optional Variables in Swift: Swift is strongly typed and insists that if there is a possibility that a variable (or constant) may not have a value at some point when the program is running, then it must be declared as optional. The variable may then either contain a value of the declared type or may be nil. The purpose is to avoid the null reference errors that can occur in other languages when someone tries to use a variable without a value. Declare a variable as optional by putting a question mark at the end of the type such as our WeatherForecast:
var forecast: WeatherForecast?
When using the values in an optional variable, the variable needs to be “unwrapped”, like removing it from a box. Consider a cardboard box labelled “Weather Forecast”; you can open it up to find a forecast object or you can find nothing, so you can’t treat it as if there is always a value there. There are several ways to unwrap and to check what is in the box, but for this problem we will force unwrapping explicitly.
The Problem with String Interpolation with Optionals:
When we tried to display the temperature in either Fahrenheit or Celsius by drilling down through the many nested levels of objects in our WeatherForecast we were getting this warning and the text on screen was gibberish:
The fix is to explicitly unwrap the values at each object level by putting an exclamation point in place of the question mark in multiple places, i.e., after each object name within the long nested object: