当前位置: 首页 > 面试题库 >

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

慕阳
2023-03-14
问题内容

我有两个问题:

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?)'

我不知道该怎么解决。


问题答案:

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  
}


 类似资料: