Swift 4将nil jsonElement更改为空字符串

时间:2018-04-04 13:43:05

标签: ios json swift xcode

根据标题,我没有运气,我已经设法通过将任何可能为零的内容添加到自己的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编程,请保持温和。我曾尝试阅读类似的主题,但无法让它发挥作用。 感谢

2 个答案:

答案 0 :(得分:3)

Just provide it a default value, e.g.:

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

Read more in Nil-Coalescing Operator section of Basic Operators in Swift:

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

答案 1 :(得分:1)

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

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