Swift convert Integer to Int

swift

Solution

You can use `numericCast()` to convert between different integer types. As the documentation states:

Typically used to do conversion to any contextually-deduced integer type.

In your case:

extension CountableRange where Bound: Strideable {

    // Extend each bound away from midpoint by `factor`, a portion of the distance from begin to end
    func extended(factor: CGFloat) -> CountableRange<Bound> {
        let theCount: Int = numericCast(count)
        let amountToMove: Bound.Stride = numericCast(Int(CGFloat(theCount) * factor))
        return lowerBound - amountToMove ..< upperBound + amountToMove
    }
}

The restriction `Bound: Strideable` is necessary to make the arithmetic `lowerBound - amountToMove` and `upperBound + amountToMove` compile.

Problem

I am doing generics programming and have something that conforms to Integer. Somehow I need to get that into a concrete Int that I can use. ``` extension CountableRange { // Extend each bound away from midpoint by `factor`, a portion of the distance from begin to end func extended(factor: CGFloat) -> CountableRange<Bound> { let theCount = Int(count) // or lowerBound.distance(to: upperBound) let amountToMove = Int(CGFloat(theCount) * factor) return lowerBound - amountToMove ..< upperBound + amountToMove } } ``` The error here is on `let theCount = Int(count)`. Which states: Cannot invoke initializer for type 'Int' with an argument list of type '(Bound.Stride)' First the error could be more helpful because `CountableRange` defines its `Bound.Stride` as `SignedInteger` (source). So the error could have told me that. So I know it is an `Integer`, but how do I actually make use of the `Integer` value?

Original source