【问题标题】:Swift 4 Change nil jsonElement to an empty stringSwift 4 将 nil jsonElement 更改为空字符串
【发布时间】:2018-09-14 02:38:49
【问题描述】:

根据标题,我对此并不走运,通过将任何可能为 nil 的内容放入其自己的 if let 中,我设法对 nil 元素进行了一个小修复,但我希望它成为一个空字符串而不是 nil,因为我稍后需要使用它。 (我认为?)

if let studentID = jsonElement["S_ID"] as? String,
let firstName = jsonElement["FirstName"] as? String,
let surname = jsonElement["Surname"] as? String,
let displayPicture = jsonElement["StudentPicture"] as? String,
let dateOfBirth = jsonElement["DateofBirth"] as? String
{
    student.studentID = studentID
    student.firstName = firstName
    student.surname = surname
    student.displayPicture = displayPicture
    student.dateOfBirth = dateOfBirth
    //    student.father = father
    //    student.guardian = guardian
    //   student.keyPerson = keyPerson
}

if let mother = jsonElement["Mother"] as? String
{
    student.mother = mother
}

我对 iOS 编程非常陌生,请温柔一点。我曾尝试阅读类似的主题,但无法正常工作。 谢谢

【问题讨论】:

    标签: ios json swift xcode


    【解决方案1】:

    只要给它一个默认值,例如:

    student.studentID = (jsonElement["S_ID"] as? String) ?? ""
    

    在 Swift 中 Basic OperatorsNil-Coalescing Operator 部分了解更多信息:

    零合并运算符(a ?? b) 解包可选的a,如果它包含一个值,或者如果a 是nil,则返回一个默认值b表达式a 始终是可选类型。 表达式b 必须与存储在a 中的类型匹配。

    【讨论】:

      【解决方案2】:

      您可以使用else 部分来处理nil 值。

      if let mother = jsonElement["Mother"] as? String {
          student.mother = mother
      } else {
          student.mother = ""
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 2013-03-03
        • 2012-08-13
        • 2015-02-25
        • 2018-03-31
        相关资源
        最近更新 更多