Xcode
Swift
swift4

Swift タプルの扱い


タプル(tuple)

備忘録

swift v4.2.1


記述

let languages = ("English", "Japanese", "French", "German")


型指定

型宣言する場合は値の数書く

let tupleType: (String, Int) = ("Swift", 1234);


型推論

var tupleInference = (111, 222, 333) // 型推論で(Int, Int, Int)

tupleInference = (1, "文字列", 999) // error(Cannot assign value of type '(Int, String, Int)' to type '(Int, Int, Int)')


取り出し

let values = (11, 22)

let (value1, value2) = values
let result = (value2 / value1)
print(value1, value2) // "11 22\n"


インデックスでのアクセス

let values = (100, 200)

let value1 = values.0
let value2 = values.1

print(value1, value2) // "100 200\n"

var values = ("AAA", "bbb")

values.1 = "BBB"
print(values) // "("AAA", "BBB")\n"


ラベル付き

let length = (height: 200, width: 300)

let size = lenght.height * length.width
print(size) // "60000\n"

var person: (lastName: String, firstName: String, age: Int)

person.lastName = "Blanks"
person.firstName = "Billy"
person.age = 63
print(person) // "(lastName: "Blanks", firstName: "Billy", age: 63)\n"