20
20

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.

Xcode6-Beta4現在のSwiftで逆Rangeを適切に扱う

Last updated at Posted at 2014-07-23

##はじめに

お断りしておきますと、「Rangeを使ったforループは気をつけよう」で指摘されている問題は、Appleも把握してます。

Release Notes

More improvements are due in forthcoming betas, addressing a variety of issues iterating over floating point ranges, constructing negative ranges, and several other known range-related problems.

##Appleの対応を待てない人は

それを踏まえた上で、Appleの対応を待てない人向けの対策を。

@infix func ..< (lhs:Int, rhs:Int)->StrideTo<Int> {
    return stride(from:lhs, to:rhs, by:(lhs <= rhs ? 1 : -1 ))
}
@infix func ... (lhs:Int, rhs:Int)->StrideThrough<Int> {
    return stride(from:lhs, through:rhs, by:(lhs <= rhs ? 1 : -1 ))
}

動作確認用コード

for i in 0..<4 { println("0..<4: \(i)") }
for i in 4..<0 { println("4..<0: \(i)") }
for i in 0...4 { println("0...4: \(i)") }
for i in 4...0 { println("4...0: \(i)") }

本当は

@infix func ..< <T:Comparable>(lhs:Int, rhs:Int)->Range<T>

で定義したいところですが、それだと**ambiguous use of ..<**って怒られちゃうので、Non-GenericにInt決めうちで。

見ての通り、..<...もただの演算子なので、当然Overloadの対象だということも覚えておくといいかも。

Dan the Bidirectional

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?