2017-10-28 169 views
0

的参数列表,我有两个问题:不能调用类型 '双' 初始化与类型 '(字符串?)'

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

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

回答

7

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

如果 amount不是零
let amount:String? = amountTF.text 
if let amountValue = amount, amountValue.characters.count <= 0 { 

} 

amountValue.characters.count <= 0才会被调用。

这个let am = Double(amount)的问题相同。 amount是可选的。

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

你的字符串是可选的,因为它有一个““,意味着它可能是零,意味着另外的方法是行不通的,您必须确保可选的量存在,那么使用它:?

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) 
相关问题