无法使用类型为'(String?)'的参数列表调用类型为'Double'的初始值设定项

dav*_*vid 10 int xcode ios swift

我有两个问题:

let amount:String? = amountTF.text
Run Code Online (Sandbox Code Playgroud)
  1. amount?.characters.count <= 0

它给出了错误:

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

它给出了错误:

Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个问题.

Bil*_*lal 15

amount?.count <= 0这里的金额是可选的.你必须确保它不是nil.

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

}
Run Code Online (Sandbox Code Playgroud)

amountValue.count <= 0只有在amount不是零时才会被调用.

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

if let amountValue = amount, let am = Double(amountValue) {
       // am  
}
Run Code Online (Sandbox Code Playgroud)


asa*_*nli 8

你的字符串是可选的,因为它有'?',意味着它可能是nil,意味着进一步的方法不起作用.你必须确保存在可选的数量然后使用它:

方式1:

// If amount is not nil, you can use it inside this if block.

if let amount = amount as? String {

    let am = Double(amount)
}
Run Code Online (Sandbox Code Playgroud)

方式2:

// If amount is nil, compiler won't go further from this point.

guard let amount = amount as? String else { return }

let am = Double(amount)
Run Code Online (Sandbox Code Playgroud)