代码之家  ›  专栏  ›  技术社区  ›  Trombone0904

Swift如果值为零,则改为设置默认值

  •  9
  • Trombone0904  · 技术社区  · 7 年前

    let strValue = String()
    textfield.stringValue = strValue!
    

    问题是 strValue 可以为零。

    if strValues.isEmpty() {
       textfield.stringValue = ""
    } else {
       textfield.stringValue = strValue!
    }
    

    但是我有没有更快更容易的方法?

    我读了一些类似的东西 ??

    更新 现在我站不住了??接线员,但在这种情况下我是怎么认识到的?

    let person = PeoplePicker.selectedRecords as! [ABPerson]
    let address = person[0].value(forProperty: kABAddressProperty) as?
            ABMultiValue
    txtStreet.stringValue = (((address?.value(at: 0) as! NSMutableDictionary).value(forKey: kABAddressStreetKey) as! String))
    

    我如何使用??操作员在我代码的最后一行?

    好的,我明白了!

    txtStreet.stringValue = (((adresse?.value(at: 0) as? NSMutableDictionary)?.value(forKey: kABAddressStreetKey) as? String)) ?? ""
    
    4 回复  |  直到 7 年前
        1
  •  26
  •   Irshad Ahmad    7 年前

    可以这样做,但strValue应该是可选类型

    let strValue:String?
    textfield.stringValue = strValue ?? "your default value here"
    
        2
  •  2
  •   Christopher H.    7 年前

    这个 ?? 是零凝聚算子,我也花了一点时间来理解。不过,它是简化代码的有用工具。一个简单的解释是“除非那是零,那么这个”所以 a ?? b 退货 a b a ?? b ?? c ?? d ?? e 返回第一个非零值,或 e 如果他们之前都是零。

    Nil-Coalescing Operator

        3
  •  2
  •   Abhijith    5 年前

    零配煤算子

    要在可选值为零时提供简单的默认值,请执行以下操作:

    let name : String? = "My name"
    let namevalue = name ?? "No name"
    print(namevalue)
    

    就在这里 隐式展开但安全 .

    此外,让代码更加简洁也很有用:

       do {
            let text = try String(contentsOf: fileURL, encoding: .utf8)
        }
        catch {print("error")}
    

    let text = (try? String(contentsOf: fileURL, encoding: .utf8)) ?? "Error reading file"
    
        4
  •  1
  •   Anil Arigela    5 年前

    您可以创建可选的字符串扩展名。我执行了以下操作,将可选字符串设置为空,如果该字符串为nil并且有效:

    extension Optional where Wrapped == String {
    
        mutating func setToEmptyIfNil() {
            guard self != nil else {
                self = ""
                return
            }
        }
    
    }