0Pricing
Swift Academy · レッスン

コレクション

コレクション

「コレクション」はCoddyKit上の無料Swift Academyレッスンです。 これはレッスン1/1です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSwift Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Swift Academyコースには全1レッスンが含まれています。

概要

こんにちは。

このレッスンでは、Swiftで特に重要なトピックの1つであるコレクション型について学びます。

それでは始めましょう。

Swiftには3種類のコレクション型があります。

Array → 順序付きコレクション型

Set → 順序を持たず、重複しないコレクション型

Dictionary → 順序を持たず、キーと値のペアで構成されるコレクション型

可変・不変

コレクション型が不変か可変かは、定義方法によって決まります。

let文で定義すると不変になり、varで定義すると可変になります。

定義した値を後から変更しない場合は、letを使用すると、コンパイラがより最適化されたコードを実行できるため、パフォーマンス上の利点があります。

Array

Array

Arrayは、データを順番に保持するために使用するコレクション型です。Swift 3では、Array内のすべての要素が同じ型である必要はありません。

基本的なArrayの定義構文を、次の例に示します。

// Let's create an empty array.
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

デフォルト値を指定した配列の作成

デフォルト値を指定した配列の作成

場合によっては、デフォルト値と特定のサイズを指定して配列を作成したいことがあります。その場合は、Arrayのイニシャライザに2つの引数を渡す必要があります。

これらの引数で、デフォルト値と配列の要素数を指定します。

var threeDoubles = Array(repeating: 0.0, count: 3)
print(threeDoubles)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
print(anotherThreeDoubles)

var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles)
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

Arrayリテラルを使ったArrayの作成

Arrayリテラルを使ったArrayの作成

前の例では、空のArrayを作成する方法を学びました。しかし、場合によってはArrayリテラルを使ってArrayを作成したいこともあります。

例を使って、その使用方法を学びましょう。

/*
We have defined a variable named catList, 
and with the [String] statement we specified 
that its type is an Array containing String elements.
*/
var catList: [String] = ["Garfield", "Tom"]
print(catList)
/*
It will understand that the array is an Array containing
String statements, since we assign a value that 
defines the variable. (Swift type inference)
*/
var shoppingList = ["Eggs", "Milk"]
print(shoppingList)

Arrayの値へのアクセス

Arrayの値へのアクセス

シーケンス内の特定のインデックスにある要素にアクセスする場合は、次の構文で呼び出すだけです。

myArray [index]

例を見てみましょう。

// We have defined an array with 3 elements of type Int.
var numbers:[Int] = [1, 5, 21]

// Arrays start from Index 0. For example, in order to reach the value 5, which is the 2nd element, we need to access the 1st index.
var a = numbers[1]
print( "Value of numbers at index 1 is \(a)" )

Arrayへの新しい要素の追加

Arrayへの新しい要素の追加

Arrayに新しい要素を追加できます。 

次の例では、catListという名前のArrayを定義しています。その次の手順で、appendメソッドを使ってこのArrayに新しい要素を追加しています。 

// The Array named catList was defined with 1 initial element.
var catList = ["Tom"]


/*
We are adding a new item with a Garfield 
value using the append method.
*/
catList.append("Garfield")
// Our array will now have 2 elements.


/*
With the + = operator, we can do the 
work that the append method does.
*/
catList += ["Sylvester"]

Arrayの特定のインデックスへのデータの追加

Arrayの特定のインデックスへのデータの追加

前の例でappendメソッドを使って追加した値は、Arrayの末尾に追加されます。しかし、特定のインデックスに追加したい場合もあります。その場合はinsertメソッドを使用します。

構文は次のようになります。

myArr.insert ("The data to add", at: index);

例を使って確認してみましょう。

var catList = ["Tom"]

catList.insert("Garfield", at: 1)

print(catList)

Arrayの特定の要素の削除

Arrayの特定の要素の削除

Array内の特定のインデックスにある要素を削除するには、removeメソッドを使用します。

var shoppingList = ["Apple", "Cherry", "Cheese"]

let shoppingListOne = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string

let shoppingListTwo = shoppingList.removeLast()
// the last item in the array has just been removed

print(shoppingListTwo)

配列の反復処理

for-inを使うと、手元にある配列を反復処理できます。

例を見てみましょう。

var shoppingList = ["Banana", "Orange", "Milk"]

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

セット

セット

順序を持たず、同じ型の要素をまとめて保持するために使用します。

名前からも分かるように、Setは集合です。Setには同じ値を持つ要素を2つ以上含めることはできません。

空のセットの作成

空のSetを作成するには、次の例のようにします。

var catSet = Set<Character>()

配列リテラルを使用したSetの作成

配列リテラルを使用したSetの作成

配列リテラルを使ってSetを作成できます。ここで代入されている値は配列のように見えますが、変数の型はSet <String>であることに注意してください。

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

警告

配列リテラルを使ってSetを作成する場合、型を定義せずに作成することはできません。Arrayと混同される可能性があるため、型を定義する必要があります。 

少なくとも、次のように使用してください。

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

Setのメソッド

Setのメソッド

例を見てみましょう。

var favoriteGenres = ["Funk"]

print("I have \(favoriteGenres.count) favorite music genres.")

if favoriteGenres.isEmpty {
    print("favoriteGenres is empty")
} else {
    print("I have particular music preferences.")
}

if favoriteGenres.contains("Funk") {
    print("Funk")
} 

Setの反復処理

Setの反復処理

SwiftのSet型には順序がありません。ただし、Setの値を反復処理するときはsortedメソッドを使用できます。このメソッドは、Setの要素を配列としてソートします。

let favoriteGenres = ["Classical","Jazz", "Hip hop"]

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

Dictionary

Dictionary

Dictionaryは、値をキーと値のペアとして保持し、順序を持たないコレクション型です。

各値は一意のキーとともに保持されます。このキーは、Dictionary内でその値を識別するIDを表します。Arrayのように順序はありません。現実世界の辞書をイメージすると分かりやすいでしょう。

そのため、順序よりも各値を識別することのほうが重要です。

Dictionary型は短縮記法 [Key: Value] で定義できます。短縮記法を使うほうが一般的です。

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

Dictionaryへのアクセス方法

Dictionaryに含まれる要素数は、countメソッドで確認できます。

また、isEmptyメソッドでDictionaryが空かどうかを確認できます。

これらのメソッドを使った例を見てみましょう。

var airports = ["LHR": "London", "IST": "Istanbul"]

print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."

if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

サブスクリプト

サブスクリプトを使って値を取得する手順は次のとおりです。結果はオプショナルとして返されます。

var airports = ["DUB":"Dublin"]

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."



//Deletion
airports["APL"] = nil

if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport."

Dictionaryの更新

上記のサブスクリプトに加えて、Dictionaryを更新するメソッドもあります。

このメソッドの特徴は、更新が行われた後に、更新前の古い値を返すことです。

var airports = ["DUB": "Dublin"]

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."

DictionaryからArrayへの変換例

DictionaryからArrayへ変換する例を以下に示します。


let airports = ["IST":"Istanbul Airport", "DUB":"Dublin Airport"]

let airportCodes = [String](airports.keys)
print(airportCodes)

let airportNames = [String](airports.values)
print(airportNames)

おめでとうございます

おめでとうございます 🎉

このレッスンでは、Swiftでコレクションを使用する方法を学びました。

次のレッスンでお会いしましょう。

コレクション — イラスト22

よくある質問

「コレクション」レッスンは無料ですか?

はい。「コレクション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Swift Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Swift Academyコースには全1レッスンが含まれています。

「コレクション」で何を学びますか?

コレクション ブラウザで直接実行するハンズオンコードでSwift Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Swift Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSwift Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/1です。

「コレクション」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSwift Academyレッスンでコードを書いて実行できますか?

はい。すべてのSwift Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

← Swift Academyに戻る