【问题标题】:Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'无法使用类型为“(String?)”的参数列表调用类型“Double”的初始化程序
【发布时间】:2017-10-28 11:19:41
【问题描述】:

我有两个问题:

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

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

【问题讨论】:

    标签: ios swift xcode int


    【解决方案1】:

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

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

    amountValue.count &lt;= 0 只会在amount 不为零时被调用。

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

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

    【讨论】:

    • 字符已被弃用 = 使用 if let amountValue = amount, !amountValue.isEmpty {...}
    【解决方案2】:

    错误的另一个原因是 amount 它不应该为 null

    let am = Double(amount!)
    

    带检查控制

    if amount != nil {
       let am = Double(amount!)
    }
    

    【讨论】:

    • 不要使用这个。 “!”永远不应该用作高级开发人员。这将在这里或那里导致无法估量的崩溃。可选项意味着是可选的,如果可选项可用,则在您编写代码的地方以及在不可用时以另一种方式去的地方是可选的。请参阅上面的答案,我们检查是否有可选选项。然后你必须考虑如果它不可用怎么办。使用 (!) 不仅会导致崩溃,还会在考虑架构时缩小您的视野。切勿在任何地方使用 ( ! )。
    • 我的解决方案解决了这个问题。解决方法是有争议的,但如果这不是真的,Apple 无论如何都不会允许它。可以认为是事先进行了一次空检查。
    • 没有。 “Apple 不允许”你是程序员,Apple 让你写好或坏的代码。上面的建议是一种常见的坏方法。
    【解决方案3】:

    你的字符串是可选的,因为它有一个'?

    方式 1:

    // If amount is not nil, you can use it inside this if block.
    
    if let amount = amount as? String {
    
        let am = Double(amount)
    }
    

    方式 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多