2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftでジェネリックなremap関数を作る

Last updated at Posted at 2014-06-09

やはりremap関数の汎用性は異常だと思います。
そこでとりあえずジェネリックな関数が欲しくなります。
ですが、どうやらC++のテンプレートとは違い、protocolに一工夫必要のようです。
//まあ、もうほとんどDouble決め打ちでいい気もしますが

protocol FourArithmeticOperations {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
}
extension Float: FourArithmeticOperations { }
extension Double: FourArithmeticOperations { }

func remap<T: FourArithmeticOperations>(value: T, #inputMin: T, #inputMax: T, #outputMin: T, #outputMax: T) -> T
{
    return (value - inputMin) * ((outputMax - outputMin) / (inputMax - inputMin)) + outputMin;
}

for i in 0...100 {
    let t = remap(Double(i), inputMin: 0.0, inputMax: 100.0, outputMin: 0.0, outputMax: M_PI * 2.0)
    let v = sin(t)
    println("i[\(i)] => \(v)")
}

こちらを参考にさせていただきました。
http://stackoverflow.com/questions/24046792/swift-generics-requiring-addition-and-multiplication-abilities-of-a-type

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?