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

时间:2022-08-13 23:09:25

I have two issues:

我有两个问题:

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

It's giving error :

它给出了错误:

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

It's giving error:

它给出了错误:

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

I don't know how to solve this.

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

2 个解决方案

#1


13  

amount?.count <= 0 here amount is optional. You have to make sure it not nil.

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

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

}

amountValue.count <= 0 will only be called if amount is not nil.

如果amount不是nil,则仅调用amountValue.count <= 0。

Same issue for this let am = Double(amount). amount is optional.

同样的问题让我=双(金额)。金额是可选的。

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

#2


6  

Your string is optional because it had a '?", means it could be nil, means further methods would not work. You have to make sure that optional amount exists then use it:

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

WAY 1:

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

if let amount = amount as? String {

    let am = Double(amount)
}

WAY 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)

#1


13  

amount?.count <= 0 here amount is optional. You have to make sure it not nil.

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

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

}

amountValue.count <= 0 will only be called if amount is not nil.

如果amount不是nil,则仅调用amountValue.count <= 0。

Same issue for this let am = Double(amount). amount is optional.

同样的问题让我=双(金额)。金额是可选的。

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

#2


6  

Your string is optional because it had a '?", means it could be nil, means further methods would not work. You have to make sure that optional amount exists then use it:

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

WAY 1:

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

if let amount = amount as? String {

    let am = Double(amount)
}

WAY 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)