[英]Swift convert Integer to Int
I am doing generics programming and have something that conforms to Integer . 我正在进行泛型编程,并且有一些符合Integer的东西。 Somehow I need to get that into a concrete Int that I can use.
不知怎的,我需要把它变成一个我可以使用的具体的Int 。
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)
. 这里的错误是
let theCount = Int(count)
。 Which states: 哪个州:
Cannot invoke initializer for type 'Int' with an argument list of type '(Bound.Stride)'
无法使用类型为'(Bound.Stride)'的参数列表调用类型'Int'的初始值设定项
First the error could be more helpful because CountableRange
defines its Bound.Stride
as SignedInteger
( source ). 首先,错误可能更有用,因为
CountableRange
将其Bound.Stride
定义为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? 所以我知道它是一个
Integer
,但我如何实际使用Integer
数值呢?
You can use numericCast()
to convert between different integer types. 您可以使用
numericCast()
在不同的整数类型之间进行转换。 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. 限制
Bound: Strideable
是使算术lowerBound - amountToMove
和upperBound + amountToMove
编译所upperBound + amountToMove
。
这应该适用于从swift 3.0开始
let theCount:Int32 = Int32(count);
If you really need that Int
, try this instead: 如果您确实需要
Int
,请尝试以下方法:
let theCount = Int(count.toIntMax())
The toIntMax()
method return this integer using Swift's widest native signed integer type (ie, Int64
on 64-bits platforms). toIntMax()
方法使用Swift 最宽的本机有符号整数类型(即64位平台上的Int64
toIntMax()
返回此整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.