gpt4 book ai didi

swift - 在多参数函数中解包可选

转载 作者:行者123 更新时间:2023-11-28 10:21:04 25 4
gpt4 key购买 nike

这个问题可能看起来很基础,但我正在尝试解开下面代码中的 middleName 可选参数。我已经在这里成功解包了可选的返回,但我仍然得到了一个 Matthew Optional("Matt") Stevenson 记录。如何打开“Matt”并删除可选的返回?

func returnFullName (name: (firstName: String, middleName: String?,
lastName: String)) -> String?
{
return ("\(name.firstName) \(name.middleName) \(name.lastName)")
}

var fullName = returnFullName(("Matthew", middleName: "Matt", lastName: "Stevenson"))

if let printFullName = fullName {
print (printFullName)
}

最佳答案

您可以使用 nil coalescing operator对于可选的 middleName属性(property)。如果值为 nil , 默认 ""将被打印,而如果该值包含非零字符串,它将被解包。

return ("\(name.firstName) \(name.middleName ?? "") \(name.lastName)")

但是请注意,您不需要让 returnFullName(..) 的返回类型函数是可选的,因为该值永远不会为零。

func returnFullName (name: (firstName: String, middleName: String?,
lastName: String)) -> String {
return ("\(name.firstName) \(name.middleName ?? "") \(name.lastName)")
}

print(returnFullName(("Matthew", middleName: "Matt", lastName: "Stevenson")))
// Matthew Matt Stevenson
print(returnFullName(("Matthew", middleName: nil, lastName: "Stevenson")))
// Matthew Stevenson <-- extra unwanted space

此外,我没有看到任何明显的理由在函数签名中使用元组,而不是为不同的名称组件使用单独的参数。因此,替代方案如下:

func returnFullName (firstName: String, middleName: String?,
lastName: String) -> String {
return "\(firstName) \(middleName ?? "") \(lastName)"
}

print(returnFullName("Matthew", middleName: "Matt", lastName: "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", middleName: nil, lastName: "Stevenson"))
// Matthew Stevenson <-- extra unwanted space

最后,为了避免 nil 的额外空间-值middleName ,我建议保留单行返回,而是使用带有 if let - else 的可选绑定(bind)子句:

func returnFullName(firstName: String, middleName: String?, lastName: String) -> String {
if let middleName = middleName {
return ("\(firstName) \(middleName) \(lastName)")
}
else {
return ("\(firstName) \(lastName)")
}
}

print(returnFullName("Matthew", middleName: "Matt", lastName: "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", middleName: nil, lastName: "Stevenson"))
// Matthew Stevenson

现在,问题涉及为给定示例展开一个可选变量,现在上面已经很好地涵盖了这一点。不过,我想我会提到,您可以使用闭包和 Swifts 内置的函数式方法来压缩您的解决方案,如下所示:

// instead of a function: make use of a closure
let returnFullName : (String, String?, String) -> String = {
[$0, $1, $2].flatMap{ $0 }.joinWithSeparator(" ") }

print(returnFullName("Matthew", "Matt", "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", nil, "Stevenson"))
// Matthew Stevenson

关于swift - 在多参数函数中解包可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com