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
}
}
然而,它似乎有效,
最佳答案
您可以使用可选绑定(bind): 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 { !$0.isEmpty ? $0 + "\ncontent" : digit } ?? digit
!$0.isEmpty
在大多数情况下甚至不需要,因此代码看起来会更好一些:history.text = history.text.map { $0 + "\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 { "\($0)€" }
它还可以用于选项:
( source )
??
有什么作用:nil 合并运算符是以下代码的简写:
a != nil ? a! : b