[swift] Optionals

alslahdk·2020년 9월 7일


A type that represents either a wrapped value or nil, the absence of a value. swift types can be optianl , which is indicated by appending ? to a type name

let shortForm: Int ? = Int("42")
let longForm: Optinal<Int> = Int("42") 

The Optinal type is an enumeration with two cases

  • none is equivalent to the nil literal
  • some(Wrapped) stores a wrapped value.
let number : Int ? = Optional.some(42)
let noNumber: Int? = Optional.none

You can't use Optinal types like non-Optional types. It is necessary unwrapping the value of an Optional instance before using it in many context. Swift provides several ways to safely unwrap optinal values.


let imagePaths = ["star": "/glyphs/star.png",
                  "portrait": "/images/content/portrait.jpg",
                  "spacer": "/images/shared/spacer.gif"]

Getting a dictionary's value using a key returns an optinal value. So

imagePaths["start"] has type Optinal<String> orString?

1. Optinal Chaining

Use postfix optinal chaining operator (postfix ?).

if imagePath["start"]?.hasSuffix(".png") == true{
  print("The star image is in PNG format")

this example uses optinal chaining to access the hasSuffix(_:) method on String? instance .

2. Using the Nil-Coalescing Operator

Using the nil-coalescing operator (??) to supply a default value in case the Optinal instance is nill. The ?? operator also work with another Optinal instance on the right-hand side. It can be chained together.

let shapePath = imagePaths["cir"] ?? imagePaths["squ"]?? defaultImagePath
// Prints "/images/default.png" 

3. Unconditional Unwrapping

When an instance of Optional is certain that contains a value, you can unconditionally unwrap the value by using the forced unwrap operator(postfix ! ). Unconditinal unwrapping a nil instance with ! triggers a runtime error

let number = Int("42")!
//prints "42"

this also can be performed optinal chaining by using the postifx ! operator

let isPNG = imagePaths["star"]!.hasSuffix(".png")
// Prints "true"

4. Optional binding

Optional binding works within a conditional if-let statement. You assign the optional to a temporary constant of corresponding non-optional type. if your optinal has a value then the statement is valid and you proceed using non-optinal constant. if not, you can handle the case with an else clause.

if let r1 = reading1,
    let r2 = reading2,
    let r3 = reading3 {
        let avgReading = (r1 + r2 + r3) / 3
} else {
    let errorString = "Instrument reported a reading that was nil."

애플 개발자 문서
IOS programming

0개의 댓글