如何在Swift 4中安全解开字典值?

问题描述 投票:0回答:1

我试图安全地解开函数中包含的字典值。我找到了另一个可行的问题的摘要,但是在打印时我不得不强行打开包装。仅在有肯定值可用时才起作用。

func emailAddress(for name: String) -> String? {
    let emails = ["daniel":"[email protected]","Kevin":"[email protected]"]
    let email = emails[name ?? "none"]
    return email

}

print(emailAddress(for: "daniel" )!)

这段代码在工作时处于打开和关闭状态。我更喜欢使用if-let 安全地解开包裹,但是当我输入此代码来解包裹时。

func emailAddress(for name: String) -> String? {
    let emails = ["daniel":"[email protected]","Kevin":"[email protected]"]
    if let email = emails[name] {
    print(email)
    } else {
        print("There is no email address")
    }
     return email
}

Swift给我各种各样的错误,我不确定问题出在哪里。可选内容已经令人困惑,现在对于字典来说,只有可选内容对我来说是一场噩梦。当我在线使用示例时,它们可以工作,但是我自己的实现是一场灾难。

我也看到了电子邮件[name ?? “ none”]是一个迅速的5功能。这可能是个问题吗?

swift function dictionary
1个回答
0
投票

使用if let时,email仅在块内可见,您需要

func emailAddress(for name: String) -> String? {
  let emails = ["daniel":"[email protected]","Kevin":"[email protected]"]
  return email[name]
}
© www.soinside.com 2019 - 2024. All rights reserved.