How do you unwrap Swift optionals?

前端 未结 5 1167
难免孤独
难免孤独 2020-11-27 04:14

How do you properly unwrap both normal and implicit optionals?

There seems to be confusion in this topic and I would just like to have a reference for all of the way

相关标签:
5条回答
  • 2020-11-27 04:58

    Since Beta 5 we have also the new coalescing operator (??):

    var a : Int?
    let b : Int = a ?? 0
    

    If the optional is != nil it is unwrapped else the value on the right of the operator is used

    0 讨论(0)
  • 2020-11-27 04:59

    I created an approach to unwrap optional value:

    // MARK: - Modules
    import Foundation
    import UIKit
    import CoreData
    
    // MARK: - PROTOCOL
    protocol OptionalType { init() }
    
    // MARK: - EXTENSIONS
    extension String: OptionalType {}
    extension Int: OptionalType {}
    extension Double: OptionalType {}
    extension Bool: OptionalType {}
    extension Float: OptionalType {}
    extension CGFloat: OptionalType {}
    extension CGRect: OptionalType {}
    extension UIImage: OptionalType {}
    extension IndexPath: OptionalType {}
    extension Date: OptionalType {}
    extension UIFont: OptionalType {}
    extension UIColor: OptionalType {}
    extension UIViewController: OptionalType {}
    extension UIView: OptionalType {}
    extension NSMutableDictionary: OptionalType {}
    extension NSMutableArray: OptionalType {}
    extension NSMutableSet: OptionalType {}
    extension NSEntityDescription: OptionalType {}
    extension Int64: OptionalType {}
    extension CGPoint: OptionalType {}
    extension Data: OptionalType {}
    extension NSManagedObjectContext: OptionalType {}
    
    prefix operator ?*
    
    //unwrapping values
    prefix func ?*<T: OptionalType>( value: T?) -> T {
        guard let validValue = value else { return T() }
        return validValue
    }
    

    You can add your custom data type also.

    Usage:-

    var myString = ?*str
    

    Hope it helps :)

    0 讨论(0)
  • 2020-11-27 05:00

    An optional type means that the variable might be nil.

    Example:

    var myString: Int? = 55
    myString = nil
    

    The question mark indicates it might have nil value.

    But if you state like this:

    var myString : Int = 55
    myString = nil
    

    It will show error.

    Now to retrieve the value you need to unwrap it:

    print(myString!)
    

    But if you want to unwrap automatically:

    var myString: Int! = 55
    

    Then:

    print(myString)
    

    No need to unwrap. Hope it will help.

    0 讨论(0)
  • 2020-11-27 05:02

    You can also create extensions for particular type and unwrap safely with default value. I did the following for the same :

    extension Optional where Wrapped == String {
        func unwrapSafely() -> String {
            if let value = self {
                return value
            }
            return ""
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:14

    There are many similarities and just a handful of differences.

    (Regular) Optionals

    • Declaration: var opt: Type?

    • Unsafely unwrapping: let x = opt!.property // error if opt is nil

    • Safely testing existence : if opt != nil { ... someFunc(opt!) ... } // no error

    • Safely unwrapping via binding: if let x = opt { ... someFunc(x) ... } // no error

    • Safely chaining: var x = opt?.property // x is also Optional, by extension

    • Safely coalescing nil values: var x = opt ?? nonOpt

    Implicitly Unwrapped Optionals

    • Declaration: var opt: Type!

    • Unsafely unwrapping (implicit): let x = opt.property // error if opt is nil

      • Unsafely unwrapping via assignment:
        let nonOpt: Type = opt // error if opt is nil

      • Unsafely unwrapping via parameter passing:
        func someFunc(nonOpt: Type) ... someFunc(opt) // error if opt is nil

    • Safely testing existence: if opt != nil { ... someFunc(opt) ... } // no error

    • Safely chaining: var x = opt?.property // x is also Optional, by extension

    • Safely coalescing nil values: var x = opt ?? nonOpt

    0 讨论(0)
提交回复
热议问题