1
1

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.

Array.dropFirst() .dropLast()はArraysliceを返してくるから元の配列と型が合わなくなる話

Last updated at Posted at 2019-01-14

掲題のとおりです。
最初こんなことをやりたかったんですが、できないです。

let str = "eabcd"
var Message = Array(str)

Message = Message.dropFirst()

こんなエラーになります。
辛いですね。

error: cannot assign value of type 'ArraySlice' to type '[Character]'

回避方法はいくつかあって、型変換してやってもいいですが、
配列の一文字目消したい!というだけの目的であれば、removeFirst()を使うといいみたいです。

let str = "eabcd"
var Message = Array(str) //["e","a","b","c","d"]

Message = Message.removeFirst() //["a","b","c","d"]

Arraysliceとは

Arraysliceがイマイチよくわかってないですが、
Array型を一時的に切り取ったもの、というイメージのよう。
別にArray型でもよくね?と思うものの、
https://developer.apple.com/documentation/swift/arrayslice

The ArraySlice type makes it fast and efficient for you to perform operations on sections of a larger array. Instead of copying over the elements of a slice to new storage, an ArraySlice instance presents a view onto the storage of a larger array. And because ArraySlice presents the same interface as Array, you can generally perform the same operations on a slice as you could on the original array.

 (拙訳)Arrayslice型は大きい配列をもっと高速かつ効率的に扱いたいアナタにピッタリ!
新しいストレージに丸々元の配列の要素コピーすんじゃなくて、
ArraySliceインスタンスが大きい配列への参照(view)を提供してくれる。
さらにarraySliceは配列と同じインターフェースを持ってるので、基本的にはもとの配列と同じように扱うことができる。

Arraysliceだとストレージ食わない?のか?

2019/12/04追記

急にArrayslice理解しました。
Array型に対して、その一部への参照というか、ポインタというかを返してくれるのがArraysliceなんですね。

つまりdropFirst(n)/dropLast(n)は、先頭からn文字/末尾からn文字の参照を返してくれるメソッドであり、当初僕がやろうとしてたことは完全にメソッドの誤用でした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?