2017-05-05 11 views
2

私はジェネリックプログラミングを行っており、Integerに従っています。何とか私はそれを私が使用できる具体的なIntに入れる必要があります。Swiftは整数を整数に変換します

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 
    } 
} 

エラーはlet theCount = Int(count)です。どの状態:

タイプの引数リスト「(Bound.Stride)」で型 'int型の初期化子を呼び出すことはできません

CountableRangeはその Bound.Stride SignedIntegerように定義されているため、エラーがより有用である可能性があり

ファースト(source)。だからエラーが私に言ったかもしれない。

私はそれがIntegerであることを知っていますが、実際にInteger値を使用するにはどうすればよいですか?

答えて

3

numericCast() を使用すると、異なる整数型を変換できます。ドキュメント は次のように述べています。

通常、コンテキストによって推定された整数型への変換に使用されます。あなたのケースでは

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 
    } 
} 

制限Bound: Strideableは、算術 lowerBound - amountToMoveupperBound + amountToMoveコンパイルする必要があります。

+0

非常にいいです、ありがとう! –

0

あなたは本当に、代わりにこれを試してIntことを必要とする場合、これはあなたがSWIFT 3.0

let theCount:Int32 = Int32(count); 
0

から始まるために働く必要があります。

let theCount = Int(count.toIntMax()) 

toIntMax()方法は、スウィフトの最も広いネイティブを使用して、この整数を返します符号付き整数型(つまり、64ビットプラットフォームではInt64)です。

関連する問題