gpt4 book ai didi

Swift可选赋值,处理nil/空字符串

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:20 26 4
gpt4 key购买 nike

我正在尝试解决 Swift 中的字符串分配问题:这里我们有一个结构:

struct Student {
var name: String
var id: String
var mentor: String?
var grade: String?
}

我们想把它解析成一个字符串,像这样:

if (mentor != nil && grade != nil) {
return "Student info: name:" + name + " id:" + id + " mentor:" + mentor! + " grade:" + grade! + "."
} else if (mentor != nil) {
return "Student info: name:" + name + " id:" + id + " mentor:" + mentor! + "."
} else if (grade != nil) {
return "Student info: name:" + name + " id:" + id + " grade:" + grade! + "."
} else {
return "Student info: name:" + name + " id:" + id + "."
}

我是Swift新手,上面的代码是基于其他语言的经验,请问在Swift中有没有更简洁的实现方式?就像处理可选的 toString() 一样,如果它是 nil 则返回一个空字符串 ""?

最佳答案

Alexander 的回答很好,并且很好地利用了高阶函数 map(),但如果您刚刚开始,这可能会让您有些不知所措。通过明智地使用 if let “optional binding”,您可以大大简化您的代码:

var result = "Student info: name:" + name + " id:" + id
if let mentor = mentor {
result += " mentor:" + mentor
}
if let grade = grade {
result += " grade:" + grade
}
result += "."

return result

或重写以避免 + 运算符:

var result = "Student info: name:\(name) id:\(id)"
if let mentor = mentor {
result.append(" mentor:\(mentor)")
}
if let grade = grade {
result.append(" grade:\(grade)")
}
result.append(".")

return result

关于Swift可选赋值,处理nil/空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499414/

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