LoginSignup
1
1

More than 5 years have passed since last update.

Swiftの配列からOut of boundsせず安全に指定範囲を抜き出す

Last updated at Posted at 2018-05-09

配列から指定範囲を抜き出すのは、こうする。
(実行環境、Xcode 9.3 + Swift 4.1)

// let array = [1, 2, 3]でも同じ。わかりやすく明示的型指定。
let array: [Int] = [1, 2, 3]
// [0, 1, 2]
print(array[0...2])
// Array<Int>ではなくArraySlice<Int>型である
print(type(of: array1[0...2]))
// 範囲外指定するとOut of boundsでクラッシュ
print(array[0...3])

Out of boundsでクラッシュするのも、Arrayでないのも引数に渡すときなど不便。

そこで拡張メソッドを作る。

extension Array where Element: Any {
    func safeSlice(start: Int, length: Int) -> Array {
        if self.count == 0 || length == 0 {
            return []
        }
        if start + length > self.count {
            return Array(self[start...(self.endIndex - 1)])
        } else {
            return Array(self[start...(start + length - 1)])
        }
    }
}

実行結果

let array = [1, 2, 3]
// []
print(array.st_safeSlice(start: 0, length: 0))
// [1]
print(array.st_safeSlice(start: 0, length: 1))
// [2, 3]
print(array.st_safeSlice(start: 1, length: 2))
// [1, 2, 3]
print(array.st_safeSlice(start: 0, length: 3))
// [2, 3]
print(array.st_safeSlice(start: 1, length: 2))
// [1, 2, 3]
// Out of boundsでクラッシュしない
print(array.st_safeSlice(start: 0, length: 4))
// [2, 3]
print(array.st_safeSlice(start: 1))
1
1
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
1
1