2017-10-28 154 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) 
相關問題