ios 无法使用类型为“(String?)”的参数列表调用类型“Double”的初始值设定项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46989131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'
提问by david
I have two issues:
我有两个问题:
let amount:String? = amountTF.text
amount?.characters.count <= 0
amount?.characters.count <= 0
It's giving error :
它给出了错误:
Binary operator '<=' cannot be applied to operands of type 'String.CharacterView.IndexDistance?' (aka 'Optional<Int>') and 'In
let am = Double(amount)
let am = Double(amount)
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.
我不知道如何解决这个问题。
回答by Bilal
amount?.count <= 0
here amount is optional. You have to make sure it not nil
.
amount?.count <= 0
这里的数量是可选的。你必须确保它不是nil
。
let amount:String? = amountTF.text
if let amountValue = amount, amountValue.count <= 0 {
}
amountValue.count <= 0
will only be called if amount
is not nil.
amountValue.count <= 0
仅当amount
不为 nil 时才会被调用。
Same issue for this let am = Double(amount)
. amount
is optional.
同样的问题let am = Double(amount)
。amount
是可选的。
if let amountValue = amount, let am = Double(amountValue) {
// am
}
回答by asanli
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:
你的字符串是可选的,因为它有一个 '?",意味着它可能为零,意味着进一步的方法将不起作用。你必须确保可选数量存在然后使用它:
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:
方式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)
回答by Asil ARSLAN
Another reason for the error is amountit should not be null
错误的另一个原因是数量不应为空
let am = Double(amount!)