ios - How to check if a UILabel is empty and append content to a label? -
new ios , swift. want best practice tips. want append content label in new line. 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 work, however,
- is there better way check text not nil , not empty?
- is there "keyword" thing "\r\n"?
you can use optional binding: if let
check if nil
.
example 1:
if let text = history.text !text.isempty { history.text! += "\ncontent" } else { history.text = digit }
or can use map
check optionals:
example 2:
history.text = history.text.map { !$0.isempty ? $0 + "\ncontent" : digit } ?? digit
!$0.isempty
in cases not needed code can bit better:
history.text = history.text.map { $0 + "\ncontent" } ?? digit
edit: what map
do:
the map method solves problem of transforming elements of array using function.
let’s have array of ints representing sums of money , want create new array of strings contains money value followed “€” character i.e. [10,20,45,32] -> ["10€","20€","45€","32€"]
.
the ugly way of doing creating new empty array, iterating our original array transforming each element , adding new array
var stringsarray = [string]() money in moneyarray { stringsarray += "\(money)€" }
using map
just:
let stringsarray = moneyarray.map { "\($0)€" }
it can used optionals:
the existing map allows apply function value inside optional, if optional non-nil. example, suppose have optional integer , want double it. write i.map { $0 * 2 }. if has value, optional of value doubled. on other hand, if nil, no doubling takes place.
(source)
what ??
do:
the nil coalescing operator (a ?? b) unwraps optional if contains value, or returns default value b if nil. expression of optional type. expression b must match type stored inside a.
the nil coalescing operator shorthand code below:
a != nil ? a! : b
Comments
Post a Comment