Featured image of post Tuple 알아보기

Tuple 알아보기

Tuple ❓

“A tuple type is a comma-separated list of types, enclosed in parentheses.”

스위프트 문서에는 “콤마로 구분된 타입의 목록으로 괄호로 묶여있다” 라고 정의되어 있다.

배열(Array)와 다른 점은 같은 배열은 같은 타입의 데이터를 담을 수 있지만 Tuple은 타입이 같지 않아도 사용가능하다는 점이 다르다.

Declaration

1
2
3
4
5
6
var 변수명: (데이터 타입 1, 데이터 타입 2, 데이터 타입 3) = (1, 2, 3)
// 으로 선언한다.

// 타입 추론이 가능하므로 데이터 타입을 생략하고
var 변수명 = ( 1,  2,  3)
//으로 사용도 가능하다.

Usage

tuple 사용은 변수명 뒤에 .을 붙여서 호출한다.

1
2
3
4
5
var jae = ("Jae", 20, 176.5)

print(jae.0) // Jae
print(jae.1) // 20
print(jae.2) // 176.5

인덱스 넘버를 사용하는 경우 어떤 데이터를 호출하는지 알기 어렵기 때문에 튜플을 선언할 때 이름을 붙여주면 좋다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var jenny = (name: "Jenny", age: 21, height: 169.7)

print(jenny.name) // Jenny
print(jenny.age) // 21
print(jenny.height) // 169.7

// Array와 마찬가지로 tuple안에 tuple을 넣어줄 수 있다.
var tuple = (1, "Hello, world!", true)
var anotherTuple = (2, (tuple))

print(anotherTuple.0) // 1
print(anotherTuple.1.0) // 2
print(anotherTuple.1.1) // Hello, world!
print(anotherTuple.1.2) // true

// 함수 타입도 가능
func a() -> Int { return 1 }
func b() -> String { return "Jae" }
func c() -> Bool { return false }

var functionTuple = (a(), b(), c())

print(functionTuple) // (1, "Jae", false)

loop 사용

배열처럼 인덱스가 있으니 tuple에서도 loop를 돌려서 값을 출력할 수 있을까?
img

For-in loop requires '(name: String, age: Int, height: Double)' to conform to 'Sequence' 라고 에러메세지 출력!

tuple은 Sequence 프로토콜을 준수하고 있지 않기 때문에 사용할 수 없다. 😭

Sequence 프로토콜을 따르고 있는 Array 안에 넣어준다면? loop를 돌릴 수 있다!!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let jae = (name: "Jae", age: 20, height: 176.5)
let jenny = (name: "Jenny", age: 21, height: 169.7)

let people = [jae, jenny]

for person in people {
    print(person)
    // (name: "Jae", age: 20, height: 176.5)
    // (name: "Jenny", age: 21, height: 169.7)

    print(person.name) // 이름 사용도 가능하다
    // Jae
    // Jenny
}

Tuple Decomposition 🔪

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let jae = (name: "Jae", age: 20, height: 176.5)

// 각각의 멤버를 상수로 저장하고 싶다면
let name = jae.name
let age = jae.age
let height = jae.height

// Decomposition 문법을 사용하면 한줄로 가능하다
let (nameOfJae, ageOfJae, heightOfJae) = jae

print(name) // Jae
print(nameOfJae) // Jae

Decomposition 문법 사용 시, 주의할 점은 모든 멤버를 다 지정해주어야 한다는 점이다.

img

모든 멤버가 다 필요하지 않다면, wildcard(_)를 사용하면 된다.

1
2
3
4
5
6
let jae = (name: "Jae", age: 20, height: 176.5)

let (name, _, height) = jae

print(name) // Jae
print(height) // 176.5

typealias 사용

tuple은 typealias을 사용하여 타입으로 지정할 수도 있다. 이렇게 타입으로 지정해주면 다른 값을 넣어 선언할 수 없고, tuple 타입의 배열도 만들 수 있다.

1
2
3
4
5
6
typealias Person = (name: String, age: Int, height: Double)

let jae: Person = (name: "Jae", age: 20, height: 176.5)
let jenny: Person = (name: "Jenny", age: 21, height: 169.7)

let People = [Person]()

img

Tuple Matching - switch 사용

튜플은 switch와 함께 사용하여 조건을 줄 수 있다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let name = (firstname:"Jae", lastname:"Kim")

switch name {
    case let(first, last) where first == last:
        print("Hello \(first) \(last)! That's indeed an interesting name")
    case let(_, last) where last == "":
        print("Hello \(name.firstname), Why didn't you share you surname?")
    case let(first, _) where first == "":
    print("Hello \(name.lastname)! You didn't share your first name")
    default:
        print("Hello \(name.firstname) \(name.lastname)!, nice to meet you!")
    }

// Hello Jae Kim!, nice to meet you!

Reference

Swift Doc - tuple type
Zedd0202 - Swift) tuple
Swift) 튜플(Tuple)에 대해 알아보자