9
10

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 2.0 で ArraySlice の挙動が変わった

Last updated at Posted at 2015-11-05

はじめに

配列の一部をスライスした配列に対して再度スライスする際の挙動が Swift 2.0 で変わっていたのでメモ

Swift 2.0 の ArraySlice ではインデックスがオリジナルのインデックスのままのため、更にスライスしようとすると範囲外アクセスになりエラーとなる模様

Swift 1.2 での動作


let arr = [1, 2, 3, 4, 5]
let sliced = arr[2..<4]
// [3, 4]
sliced[0..<1]
// [3]

Swift 2.0 での動作


let arr = [1, 2, 3, 4, 5]
let sliced = arr[2..<4]
// [3, 4]
sliced[0..<1] // fatal error: Negative ArraySlice index is out of range 

  1. [_, _, 3, 4, _]

    • 初回スライス時
  2. sliced[0..<1]

    • 二回目のスライスを行う
  3. [x, _, 3, 4, _]

    • 0..<1 は範囲外!

対応方法

一旦 Array にしてしまう、以上


let arr = [1, 2, 3, 4, 5]
let sliced = Array(arr[2..<4])
// [3, 4]
sliced[0..<1]
// [3]

9
10
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
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?