简体   繁体   English

Swift可选分配,处理零/空字符串

[英]Swift optional assignment, deal with nil/empty string

I'm trying to solve an string assignment problem in Swift: Here we have a struct: 我正在尝试解决Swift中的字符串分配问题:这里有一个结构:

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

And we want to parse it into a string, something like: 我们想将其解析为字符串,例如:

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 + "."
}

I'm new to the Swift, the code above is based on other language's experience, I'm wondering if there's any more concise way to achieve that in Swift? 我是Swift的新手,上面的代码基于其他语言的经验,我想知道在Swift中是否还有其他更简洁的方法可以实现这一目标? Like deal with optional toString(), if it's nil then return a empty string ""? 像处理可选的toString()一样,如果它为nil,则返回一个空字符串“”?

Alexander's answer is good, and makes good use of the higher order function map(), but it might be a bit over your head if you're just starting out. Alexander的答案很好,并充分利用了高阶函数map(),但如果您刚开始,可能会有点麻烦。 You could simplify your code quite a bit with judicious use of if let "optional binding": 您可以通过明智地使用if let “可选绑定”来简化代码:

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

Or rewritten to avoid the + operator: 或重写为避免+运算符:

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

Here are the improvements I would make: 这是我会做的改进:

Firstly, you should remove the unnecessary parentheses around the if predicates. 首先,应删除if谓词周围不必要的括号。 You may be used to them from other C-like languages, but in Swift they're just noise. 您可能已经从其他类似C的语言中习惯了它们,但是在Swift中它们只是噪音。

Secondly, you should replace string concatenation ( + ) with interpolation. 其次,您应该将插值( + )替换为插值。 It has much faster compile times (operator type inference slows the compiler substantially), and will soon (with the rework of string interpolation) have better runtime performance (no redundant string allocation). 它具有更快的编译时间(运算符类型推断会大大降低编译器的速度),并且很快(通过字符串内插的重做)将具有更好的运行时性能(无冗余的字符串分配)。

Next, I would use Optional.map to construct all the parts of the sentence that are optional. 接下来,我将使用Optional.map构造句子的所有Optional.map部分。 Then, I would default them to the empty string, if they're nil . 然后,如果它们为nil ,则将它们默认为空字符串。

Then, I would take all the segments of the string, and join them together with a space as a separator: 然后,我将把字符串的所有段,并用空格将它们连接在一起作为分隔符:

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

extension Student: CustomStringConvertible {
    var description: String {
        let start = "Student info:"
        let nameSegment = "name: \(self.name)"
        let idSegment = "id: \(self.id)"
        let mentorSegment = self.mentor.map { "mentor: \($0)" } ?? ""
        let gradeSegment = self.grade.map { "grade: \($0)" } ?? ""
        return [start, nameSegment, idSegment, mentorSegment, gradeSegment].joined(separator: " ")
    }
}

print(Student(name: "Bob", id: "id123", mentor: "Mr. Mentor", grade: "123"))
// => Student info: name: Bob id: id123 mentor: Mr. Mentor grade: 123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM