Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

null

ios

swift

New to ios and swift. Want some best practice tips. I want to append content to a label in a new line. My try:

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

  1. Is there a better way to check the text is not nil and not empty?
  2. Is there a "keyword" thing for "\r\n"?
like image 428
Logan W Avatar asked Feb 11 '23 08:02

Logan W


2 Answers

You can use optional binding: if let to check if something is nil.

Example 1:

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

Or you can use map to check for optionals:

Example 2:

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

!$0.isEmpty is in most cases not even needed so the code can look a bit better:

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

EDIT: What does map do:

The map method solves the problem of transforming the elements of an array using a function.

Let’s say we have an array of Ints representing some sums of money and we want to create a new array of strings that contains the money value followed by the “€” character i.e. [10,20,45,32] -> ["10€","20€","45€","32€"].

The ugly way of doing this is by creating a new empty array, iterating our original array transforming each element and adding it to the new array

var stringsArray = [String]()

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

Using map is just:

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

It can also be used for optionals:

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 { $0 * 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)

What does ?? do:

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.

The nil coalescing operator is shorthand for the code below:

a != nil ? a! : b
like image 73
Eendje Avatar answered Feb 13 '23 06:02

Eendje


What about using something like this:

if let text = history.text where !text.isEmpty {
    history.text = "\(text)\nsome content"
}
like image 42
mohamede1945 Avatar answered Feb 13 '23 05:02

mohamede1945