根据标题,我对此没有任何运气,我已经通过将任何可能为零的内容放入到自己的if let中来对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编程很在行,请温柔点。我试着读过类似的话题,但没能让它起作用。谢谢
发布于 2018-04-04 13:48:46
您可以使用else部件来处理nil值。
if let mother = jsonElement["Mother"] as? String {
student.mother = mother
} else {
student.mother = ""
}发布于 2018-04-04 13:46:42
只需提供一个默认值,例如:
student.studentID = (jsonElement["S_ID"] as? String) ?? ""请参阅Swift中https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html的Nil-聚结运算符部分的更多内容:
如果一个可选的
a包含一个值,则为零合并操作符a;如果是nil,则返回一个默认值b。表达式a始终是可选类型。表达式b必须与存储在a中的类型匹配。
https://stackoverflow.com/questions/49652612
复制相似问题