見出し画像

[Swift] tupleの使いかた

Swiftには型の違う複数の値を格納するためにtuple()というメソッドがあるらしい

使い方の例

宣言

var tupleJuice = (name: "3種のベリーヨーグルト", size: "S", price: 360)

//なお引数は簡潔に書くこともできる
var (name, size, price) = ("Coffee", "S", 224)

出力

普通に変数を出力したい時と同様

print(tupleJuice.name) -> "3種のベリーヨーグルト"

print(name) -> "Coffee"

出力したくない値を隠すこともできる

//出力したくない値は_でなかったことにする
var (unta, _, untu) = ("うんた!w", "うんち!w", "うんつ!w")

print(unta, _, untu)

-> "うんた!w, うんつ!w"

Structとかenumの代用で使えるじゃん!シンプルで好き!と思ったけど

Tuples are useful for temporary groups of related values. They’re not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple.

https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#

>They’re not suited to the creation of complex data structures.

複雑なデータ構造の時にはtupleを使うのには適していない

>Tuples are useful for temporary groups of related values.

Tuplesは一時的な値のバインドに有用ですよ

とのことらしいです

簡単なデータの受け渡しをするときはtypealiasを使いましょう、とのこと

typealias PersonalInfo = (name: String, address: String, age: Int)

let personalInfo = PersonalInfo(name: "nabe", address: "Tokyo", age: 20)

https://qiita.com/t__nabe/items/7acb43980a74edf20678

この記事が気に入ったらサポートをしてみませんか?