swift - 无法匹配类型的值

标签 swift swift3

我刚开始使用 Swift 3,我正在将 Rails 项目转换为 swift(我学习时的副项目)

相当简单,我有一个正在转换的 Rails 语句,我在 Xcode 中收到许多红色错误:

let startingPoint: Int = 1
let firstRange: ClosedRange = (2...10)
let secondRange: ClosedRange = (11...20)

func calc(range: Float) -> Float {
  switch range {
    case startingPoint:
     return (range - startingPoint) * 1 // or 0.2
    case firstRange:
     return // code
    default:
     return //code
  }
}

calc 将有一个 IntFloat 值:1010.50

错误是:

Expression pattern of type ClosedRange cannot match values of type Float

Binary operator - cannot be applied to operands of type Float and Int

我了解这些错误,但我不知道要搜索什么来更正错误。你能给我指出正确的方向吗?

最佳答案

Swift 是强类型的。每当你使用变量或将某些东西作为函数参数传递时,Swift 会检查它的类型是否正确。您不能将字符串传递给需要整数等的函数。Swift 在编译时进行此检查(因为它是静态类型的)。​​

要遵守该规则,请尝试将您的代码更改为:

let startingPoint: Float = 1
let firstRange: ClosedRange<Float> = (2...10)
let secondRange: ClosedRange<Float> = (11...20)

func calc(range: Float) -> Float {
    switch range {
    case startingPoint:
        return (range - startingPoint) * 1 // or 0.2
    case firstRange:
    return 1.0 // 1.0 is just an example, but you have to return Float since that is defined in the method
    default:
        return 0.0 // 0.0 is just an example, put whatever you need here
    }
}

关于swift - 无法匹配类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103114/

相关文章:

ios - swift 4 : Navigation Bar looks different for the next page

ios - 可以延迟 Today Extensions (iOS) 上的功能执行

swift - 在迭代期间使用 forEach 从集合中删除元素

swift - 如何使用 coredata 从上到下对 tableview 项目进行排序

ios - TableView 在观察 .childAdded 时继续添加行,即使在 Firebase 中未添加子项也是如此

ios - 使所有按钮变圆

ios - 面向协议(protocol)的编程示例在 swift 3.0 中不起作用

ios - XCode8 Swift3 - 打开联系人列表并通过单击检索数据时出现问题

xcode - 是否可以在 Xcode 8/Swift 3 Beta for iOS 9 中发布应用程序?

ios - 状态恢复仅在连接到 Xcode 时有效