Swift convert Integer to Int

I am programming generics and have something that matches Integer . Somehow I need to do this on a specific 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 is here on let theCount = Int(count)

. What states:

Cannot call initializer for type 'Int' using argument list of type '(Bound.Stride)'

The error may be more helpful at first as it CountableRange

identifies it Bound.Stride

as SignedInteger

( source ). So a mistake could tell me that.

So, I know what it is Integer

, but how can I use the value Integer

?

+3


source to share


3 answers


You can use numericCast()

to convert between different integer types. As the documentation says:

Typically used to convert to any context sensitive 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

must be made arithmetic lowerBound - amountToMove

and upperBound + amountToMove

.

+4


source


this should work for you since swift 3.0



let theCount:Int32 = Int32(count);

      

0


source


If you really need Int

to try this instead:

let theCount = Int(count.toIntMax())

      

The method toIntMax()

returns this integer using Swifts with a wide native integer type (i.e. Int64

on 64-bit platforms).

0


source







All Articles