你真的应该小心清理你的格式。这是马虎。此外,如果存在,您应该使用if let
有条件地解包和绑定可选值中的值:
if let displayName = messages[i].header.sender.displayName {
snd = displayName
}
else {
snd = "No Name"
}
更好的是,您可以使用nil-coalescing 运算符 ( ??
):
let snd = messages[i].header.sender.displayName ?? "No Name"
回应您编辑的问题。同样,您的代码完全是一团糟。此代码使您看起来像是要花钱输入字母。msgs
? snd
? sbj
? 真的吗?messages
, sender
,subject
有那么难写吗?想想它们对你的代码的读者来说是多么的干净和容易。甚至还没有修复它,只需看看这段代码在经过一些清理后更易于管理:
fetchOperation?.start { (error, messages, vanished) -> Void in
let sender = "No Name"
if messages != nil {
let messages = msgs as! [MCOIMAPMessage]
for i in 0..<messages.count {
let dateString = messages[i].header.date.description
let subject = messages[i].header.subject!
print(subject)//HERE ITS GIVE ME SBJ THTS MEAN NO NIL IN IT NIL COMES when i used for display name
let sender = messages[i].header?.sender?.displayName? ?? "No Name"
//its give fetal error unwrap optional value for "snd"
}
}
}
现在,这是我修复它的尝试:
fetchOperation?.start { (error, messages, vanished) -> Void in
guard let messages = messages as? [MCOIMAPMessage] else { return }
for message in messages {
let header = message.header
//FIXME: .description is a bad idea. use dateformatter to internationalize.
let dateString = header.date.description
let subject = header.subject
print(subject)
let senderDisplayName = header.sender.displayName ?? "No Name"
}
}