Generic Initializer

init(_:)

Creates an array containing the elements of a sequence. あるシーケンスの要素を含んでいる配列を作成します。

Declaration 宣言

init<S>(_ s: S) where Element == S.Element, S : Sequence

Parameters パラメータ

s

The sequence of elements to turn into an array. 配列になることになる、いくらかの要素からなるシーケンス。

Discussion 解説

You can use this initializer to create an array from any other type that conforms to the Sequence protocol. For example, you might want to create an array with the integers from 1 through 7. Use this initializer around a range instead of typing all those numbers in an array literal. あなたはこのイニシャライザを使って、Sequenceプロトコルに準拠する何か他の型から配列を作成することができます。例えば、あなたは配列を1から7までの整数で作成したいかもしれません。それらの数をすべて配列リテラルの中にタイプするの代わりに、ある範囲を取り囲むようにこのイニシャライザを使ってください。


let numbers = Array(1...7)
print(numbers)
// Prints "[1, 2, 3, 4, 5, 6, 7]"

You can also use this initializer to convert a complex sequence or collection type back to an array. For example, the keys property of a dictionary isn’t an array with its own storage, it’s a collection that maps its elements from the dictionary only when they’re accessed, saving the time and space needed to allocate an array. If you need to pass those keys to a method that takes an array, however, use this initializer to convert that list from its type of LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String]. あなたはまたこのイニシャライザを使って、逆に複雑なシーケンスまたはコレクション型を配列へと変換することができます。例えば、辞書のkeysプロパティはそれ自身のストレージを持つことになる配列ではありません、それはコレクションです、それはそれの要素らをそれらがアクセスされた時に限り辞書からマップします、そして配列を割り当てるのに必要とされる時間と空間を節約しています。しかしながら、あなたが配列を取るメソッドにそれらキーを渡す必要があるならば、このイニシャライザを使ってそのリストをそれの型のLazyMapCollection<Dictionary<String, Int>, Int>から単純な[String]へ変換してください。


func cacheImages(withNames names: [String]) {
    // custom image loading and caching
 }


let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
        "Gold": 50, "Cerise": 320]
let colorNames = Array(namedHues.keys)
cacheImages(withNames: colorNames)


print(colorNames)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"

Relationships 関係

From Protocol 由来プロトコル

See Also 参照

Creating an Array 配列の作成