mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 01:51:38 +00:00
Added clearer description of Optionals and Unwrapping. Minor typo changes as well.
This commit is contained in:
parent
5dac348b72
commit
ad16a31c07
@ -58,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
|
|||||||
print("Build value: \(buildValue)") // Build value: 7
|
print("Build value: \(buildValue)") // Build value: 7
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Optionals are a Swift language feature that allows you to store a `Some` or
|
Optionals are a Swift language feature that either contains a value,
|
||||||
`None` 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
|
Because Swift requires every property to have a value, even nil must be
|
||||||
explicitly stored as an Optional value.
|
explicitly stored as an Optional value.
|
||||||
@ -80,6 +81,12 @@ if someOptionalString != nil {
|
|||||||
}
|
}
|
||||||
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
|
// implicitly unwrapped optional
|
||||||
var unwrappedString: String! = "Value is expected."
|
var unwrappedString: String! = "Value is expected."
|
||||||
// same as above, but ! is a postfix operator (more syntax candy)
|
// 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.
|
// Swift has support for storing a value of any type.
|
||||||
// AnyObject == id
|
// 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
|
var anyObjectVar: AnyObject = 7
|
||||||
anyObjectVar = "Changed value to a string, not good practice, but possible."
|
anyObjectVar = "Changed value to a string, not good practice, but possible."
|
||||||
|
|
||||||
@ -296,7 +303,7 @@ print(numbers) // [3, 6, 18]
|
|||||||
// MARK: Structures
|
// MARK: Structures
|
||||||
//
|
//
|
||||||
|
|
||||||
// Structures and classes have very similar capabilites
|
// Structures and classes have very similar capabilities
|
||||||
struct NamesTable {
|
struct NamesTable {
|
||||||
let names = [String]()
|
let names = [String]()
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user