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
?
source to share
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
.
source to share