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,
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
What about using something like this:
if let text = history.text where !text.isEmpty {
history.text = "\(text)\nsome content"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With