Ios 如何检查UILabel是否为空并将内容附加到标签?
ios和swift的新功能。想要一些最佳实践技巧。 我想将内容附加到新行中的标签。我的尝试:Ios 如何检查UILabel是否为空并将内容附加到标签?,ios,swift,null,Ios,Swift,Null,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"
@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
}
}
不过,这似乎是可行的
使用这样的东西怎么样:
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 { !$0.isEmpty ? $0 + "\ncontent" : digit } ?? digit
$0.isEmpty
在大多数情况下甚至不需要,因此代码看起来会更好一些:
history.text = history.text.map { $0 + "\ncontent" } ?? digit
编辑:什么是map
do:
映射方法解决了使用函数变换数组元素的问题
假设我们有一个整数数组,表示一些金额,我们希望创建一个新的字符串数组,其中包含货币值,后跟“€”字符,即[10,20,45,32]->[“10欧元”,“20欧元”,“45欧元”,“32欧元]
这样做的丑陋方式是创建一个新的空数组,迭代原始数组,变换每个元素并将其添加到新数组中
var stringsArray = [String]()
for money in moneyArray {
stringsArray += "\(money)€"
}
使用map
只是:
let stringsArray = moneyArray.map { "\($0)€" }
它也可用于选项:
现有映射允许您将函数应用于可选值(如果该可选值为非nil)中的值。例如,假设您有一个可选的整数i,并且希望将其加倍。您可以编写i.map{$0*2}。如果我有一个值,你得到一个可选值,该值加倍。另一方面,如果i为零,则不会发生加倍
()
什么是?
做的:
如果可选a包含值,则nil合并运算符(a??b)将其展开;如果a为nil,则返回默认值b。表达式a始终是可选类型。表达式b必须与存储在a中的类型匹配
nil凝聚运算符是以下代码的简写:
a != nil ? a! : b
我找不到更好的编程解决方案,但使用故事板,您可以假设“历史”标签具有非零值。您能简要解释一下第二个示例吗?什么是
map
功能???
对我来说是一种新的语法糖。编辑答案,如果它回答了你的问题,请标记为已回答:)