William Entriken
William Entriken

Reputation: 39253

Swift convert Integer to Int

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?

Upvotes: 3

Views: 877

Answers (3)

Paulo Mattos
Paulo Mattos

Reputation: 19339

If you really need that Int, try this instead:

let theCount = Int(count.toIntMax())

The toIntMax() method return this integer using Swift’s widest native signed integer type (i.e., Int64 on 64-bits platforms).

Upvotes: 0

Martin R
Martin R

Reputation: 539735

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.

Upvotes: 4

AppleCiderGuy
AppleCiderGuy

Reputation: 1297

this should work for you starting from swift 3.0

let theCount:Int32 = Int32(count);

Upvotes: 0

Related Questions