如何检查 UILabel 是否为空并将内容附加到标签?

How to check if a UILabel is empty and append content to a label?

ios 和 swift 的新功能。想要一些最佳实践技巧。 我想将内容附加到新行中的标签。我的尝试:

@IBOutlet weak var history: UILabel!
@IBAction func appendContent() {
    if history.text != nil  && !history.text!.isEmpty  {
        history.text = history.text!  + "\r\n" + "some content"
    }
    else{
        history.text = digit
    }
}

它似乎有效,但是,

  1. 有没有更好的方法来检查文本不为零且不为空?
  2. “\r\n”是否有 "keyword" 项?

使用这样的东西怎么样:

if let text = history.text where !text.isEmpty {
    history.text = "\(text)\nsome content"
}

您可以使用可选绑定:if let 来检查是否有内容 nil

示例 1:

if let text = history.text where !text.isEmpty {
    history.text! += "\ncontent"
} else {
    history.text = digit
}

或者您可以使用 map 检查选项:

示例 2:

history.text = history.text.map { ![=11=].isEmpty ? [=11=] + "\ncontent" : digit } ?? digit

![=19=].isEmpty 在大多数情况下甚至不需要,因此代码看起来会更好一些:

history.text = history.text.map { [=12=] + "\ncontent" } ?? digit

编辑:map 做什么:

map 方法解决了使用函数转换数组元素的问题。

假设我们有一个 Int 数组,表示一些金额,我们想要创建一个新的字符串数组,其中包含货币值后跟“€”字符,即 [10,20,45,32] -> ["10€","20€","45€","32€"].

这样做的丑陋方法是创建一个新的空数组,迭代我们的原始数组,转换每个元素并将其添加到新数组

var stringsArray = [String]()

for money in moneyArray {
    stringsArray += "\(money)€"
}

使用 map 只是:

let stringsArray = moneyArray.map { "\([=14=])€" }

它也可以用于选项:

The existing map allows you to apply a function to the value inside an optional, if that optional is non-nil. For example, suppose you have an optional integer i and you want to double it. You could write i.map { [=24=] * 2 }. If i has a value, you get back an optional of that value doubled. On the other hand, if i is nil, no doubling takes place.

(source)

??是做什么的:

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

对于以下代码,nil 合并运算符是 shorthand:

a != nil ? a! : b