Added clearer description of Optionals and Unwrapping. Minor typo changes as well.

This commit is contained in:
Clayton Walker 2015-10-06 23:36:32 -04:00
parent 5dac348b72
commit ad16a31c07

View File

@ -58,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
print("Build value: \(buildValue)") // Build value: 7
/*
Optionals are a Swift language feature that allows you to store a `Some` or
`None` value.
Optionals are a Swift language feature that either contains a value,
or contains nil (no value) to indicate that a value is missing.
A question mark (?) after the type marks the value as optional.
Because Swift requires every property to have a value, even nil must be
explicitly stored as an Optional value.
@ -80,6 +81,12 @@ if someOptionalString != nil {
}
someOptionalString = nil
/*
To get the underlying type from an optional, you unwrap it using the
force unwrap operator (!). Only use the unwrap operator if you're sure
the underlying value isn't nil.
*/
// implicitly unwrapped optional
var unwrappedString: String! = "Value is expected."
// same as above, but ! is a postfix operator (more syntax candy)
@ -94,7 +101,7 @@ if let someOptionalStringConstant = someOptionalString {
// Swift has support for storing a value of any type.
// AnyObject == id
// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc)
// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Changed value to a string, not good practice, but possible."
@ -296,7 +303,7 @@ print(numbers) // [3, 6, 18]
// MARK: Structures
//
// Structures and classes have very similar capabilites
// Structures and classes have very similar capabilities
struct NamesTable {
let names = [String]()