小编典典

无法为类型为'(String?)'的参数列表调用类型为'Double'的初始化程序

swift

我有两个问题:

let amount:String? = amountTF.text
  1. amount?.characters.count <= 0

它给出了错误:

Binary operator '<=' cannot be applied to operands of type 'String.CharacterView.IndexDistance?' (aka 'Optional<Int>') and 'In
  1. let am = Double(amount)

它给出了错误:

Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'

我不知道该怎么解决。


阅读 230

收藏
2020-07-07

共1个答案

小编典典

amount?.count <= 0这里的金额是可选的。您必须确保没有nil

let amount:String? = amountTF.text
if let amountValue = amount, amountValue.count <= 0 {

}

amountValue.count <= 0仅在amount不为nil时被调用。

同样的问题let am = Double(amount)amount是可选的。

if let amountValue = amount, let am = Double(amountValue) {
       // am  
}
2020-07-07