Name convention for unwrapped value in Swift

后端 未结 2 1625
长发绾君心
长发绾君心 2021-01-12 04:48

When I unwrap a value in Swift, I\'m always uncertain on how to name the variabile which will contain it:

override func touchesCancelled(touches: Set

        
相关标签:
2条回答
  • You can assign the same name to an unwrapped variable as the optional.

    Preferred:

    var subview: UIView?
    var volume: Double?
    
    // later on...
    if let subview = subview, let volume = volume {
      // do something with unwrapped subview and volume
    }
    

    Not preferred:

    var optionalSubview: UIView?
    var volume: Double?
    
    if let unwrappedSubview = optionalSubview {
      if let realVolume = volume {
        // do something with unwrappedSubview and realVolume
      }
    }
    

    Taken from The Official raywenderlich.com Swift Style Guide. However these are just guidelines and other conventions may be just fine.

    0 讨论(0)
  • 2021-01-12 05:05

    One may also use guard-let construct to unwrap optionals. However, guard creates a new variable which will exist outside the else statement so the naming options available for the unwrapped variable is different when compared to if-let construct.

    Refer the code example below:

    import Foundation
    
    let str = Optional("Hello, Swift")
    
    func sameName_guard() {
        // 1. All Good
        // This is fine since previous declaration of "str" is in a different scope
        guard let str = str else {
            return
        }
    
        print(str)
    }
    
    func differentName_guard() {
        let str1 = Optional("Hello, Swift")
        // 2. ERROR
        // This generates error as str1 is in the same scope
        guard let str1 = str1 else {
            return
        }
    
        print(str1)
    }
    
    sameName_guard()
    differentName_guard()
    
    0 讨论(0)
提交回复
热议问题