LoginSignup
14
15

More than 5 years have passed since last update.

Swift さくっと確認したい基礎文法 [タプル(Tuple)]

Last updated at Posted at 2015-04-11

タプル(tuple)

複数の値を一個の定数、または変数で扱えるようになる。
配列(Array)や辞書(Dictionary)と似た目的で使えるが、
タプルは値を追加、削除するなど値の個数を変えることができない。

let drink = ("coffee", 320)
var price = (240,360,1000)

タプルの種類と取り出し方

var 変数名 = (値1,値2,値3)

var price = (240,360,1000)

println(price.0) // 240
println(price.1) // 360
println(price.2) // 1000

var 変数名 = (値1,値2,(値3,値4))

下記のように、タプルの中にタプルを入れることも可能です。

var price = (240,360,("hoge",350))

println(price.0) // 240
println(price.1) // 360
println(price.2) // (hoge,350)
println(price.2.0) // hoge

(変数名,変数名) = (値1,値2)

var (price, product) = (320, "coffee")

println(price) // 320
println(product) // coffee

var 変数名 = (ラベル:値1, ラベル:値2, ラベル:値3, ...)

var drink = (coffee:320, tea:240, latte:420)

println(drink.coffee) // 320
println(drink.tea) // 240
println(drink.latte) // 420

var 変数名 : (ラベル:型, ラベル:型, ...)

型を指定したタプルを持つ変数drinkを宣言。

var drink : (name: String, price: Int)

drink.name = "coffee"
drink.price = 320

println(drink) // (coffee, 320)

その他

型の指定

let drink: (String, Int) = ("coffee", 320)
var price: (Int, Int, Int) = (240,360,1000)

タプルも型推論されるため、
下記の場合、エラーを起こす。
※(String, Int)に(String, Double)を代入しようしたため。

let drink = ("coffee", 320) // (String, Int)
drink = ("tea",200.0) // エラー (String, Double)

ワイルドカードで不要な値を無視

下記のようにワイルドカード『_』を使うことで
不要な値は無視できる。

let status = (200, "OK")

let (code, _) = status
println(code)

let (_, message) = status
println(message)
"200"
"OK"
14
15
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
14
15