根据标题,我没有运气,我已经设法通过将任何可能为零的内容添加到自己的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编程,请保持温和。我曾尝试阅读类似的主题,但无法让它发挥作用。 感谢
答案 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 optionala
if it contains a value, or returns a default valueb
if a isnil
. The expressiona
is always of an optional type. The expressionb
must match the type that is stored insidea
.
答案 1 :(得分:1)
您可以使用else
部分来处理nil
值。
if let mother = jsonElement["Mother"] as? String {
student.mother = mother
} else {
student.mother = ""
}