AnotherNewCoder
AnotherNewCoder

Reputation: 93

Assign an optional value to a UItextfield / UIlabel which aren't a string

I have an app with club -> members -> transactions, which are hierarchical. Now I want to implement the function, to edit e.g. the amount of a transaction. The reason of a transaction isn't difficult, but I cannot assign a optional type of a Double? to a textfield or label.

So my question is: How can I assign this to it?/ How can I convert it to a string?

This error is shown to me : Cannot invoke initializer for type 'String' with an argument list of type '(Double?)/(Date?)'

This is my code:

reasonlbl.text = transaction?.reason
dateLbl.text = String(transaction?.date)
amountLbl.text = String(transaction?.money)

Upvotes: 0

Views: 104

Answers (4)

Shehata Gamal
Shehata Gamal

Reputation: 100543

You can try

if let money = transaction?.money {
    amountLbl.text = "\(money)"
}

//

if let date  = transaction?.date {
  let formatter = DateFormatter()
  formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // set it as your format
  dateLbl.text = formatter.string(from:date)
}

Upvotes: 2

Vlad Z.
Vlad Z.

Reputation: 3451

Ideally, you would want to do safety checks before doing that, like this:

guard transaction = transaction else {
  return
}

or

if let date = transaction.date {
...your code
}

also if you want, you can assign default values if transactoin object is null

let date = transaction?.date ?? Date()

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd 'at' HH:mm"

let dateString = formatter.string(from: date)

Another approach is following:

amountLbl.text = "\(transaction?.money ?? 0)"

Upvotes: 2

Andrea
Andrea

Reputation: 26383

To convert a number into a string you can use a NumberFormatter (documentation) they are an amazing object, because they not only convert a number to a text or viceversa but they also take into account the current locale on user device, for instance they modify the decimal seprator.
For the date is the same you should use a DateFormatter(documentation).

let formatter = NumberFormatter()
formatter.numberStyle = .currency
amountLbl.text = formatter.string(from: transaction!.money) 

let dateFormatter = DateFormatter()
 dateFormatter.dateStyle = .medium
 dateLbl.text = dateFormatter.string(from: transaction!.date)

Pay attention that used force unwrap for your transaction object, but you MUST handle the correct unwrapping or it will crash.

Upvotes: 0

Eric Yang
Eric Yang

Reputation: 2750

amountLbl.text = String(format: "%f", transaction?.money)

A similar conversion would happen for date.

Upvotes: 0

Related Questions