How to check if UILabel is empty and add content to shortcut?

New to ios and fast. Want tips on best practice. I want to add content to a label in a new line. My attempt:

@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
    }
}

It seems to work, however,

  • Is there a better way to verify that the text is not null and not empty?
  • Is there a "keyword" for "\ r \ n"?
+4
source share
2 answers

You can use optional binding: if letto check if there is something nil.

Example 1:

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

Or you can use mapto check additional parameters:

Example 2:

history.text = history.text.map { !$0.isEmpty ? $0 + "\ncontent" : digit } ?? digit

!$0.isEmpty in most cases it’s not even needed, so the code may look a little better:

history.text = history.text.map { $0 + "\ncontent" } ?? digit

EDIT: What does map:

.

, Ints, , , , "€", .. [10,20,45,32] -> ["10€","20€","45€","32€"].

- , ,

var stringsArray = [String]()

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

map :

let stringsArray = moneyArray.map { "\($0)€" }

:

, - -. , , i, . i.map {$ 0 * 2}. , . , , .

()

??:

nil coalescing (a? b) a, , b, a nil. a . b , .

nil :

a != nil ? a! : b
+7

, - :

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

Source: https://habr.com/ru/post/1584685/


All Articles