Sylar
Sylar

Reputation: 12072

Cannot match values of type

I'm just starting out with Swift 3 and I'm converting a Rails project to swift (side project while I learn)

Fairly simple, I have a Rails statement Im converting and Im getting many red errors in 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 will either have an Int or Float value: 10 or 10.50

Errors are:

Expression pattern of type ClosedRange cannot match values of type Float

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

I understand the errors but I dont know what to search for to correct it. Could you point me in the right direction, please?

Upvotes: 1

Views: 7874

Answers (2)

Prientus
Prientus

Reputation: 733

For the first error, you might want to specify ClosedRange to be of type Floats. Something similar to:

let firstRange: ClosedRange<Float> = (2...10)

For the second error, the problem is you are trying to compare a Float (range:Float) with an Int (startingPoint). So I would suggest you convert the startingPoint variable to a Float as well.

Upvotes: 0

JPetric
JPetric

Reputation: 3918

Swift is strongly typed. Whenever you use a variable or pass something as a function argument, Swift checks that it is of the correct type. You can't pass a string to a function that expects an integer etc. Swift does this check at compile time (since it's statically typed).

To adhere by that rules, try changing your code to this:

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
    }
}

Upvotes: 4

Related Questions