Swift - Tuple

이원석·2024년 11월 19일

Swift

목록 보기
11/38

Tuple(튜플)

Tuple은 스위프트 타입 중 하나로 서로 다른 타입들을 그룹으로 묶어서 하나의 타입을 만든다.

선언 및 접근

  • 튜플을 선언한 후엔 자료형 및 멤버의 갯수 수정 불가

unnamed

let x: (String, Int, Double) = ("hello", 5, 0.85)
print(x.0) // hello
print(x.1) // 5
print(x.2) // 0.85

let (word, number, value) = x
print(word)  // hello
print(number)// 5
print(value) // 0.85

named

let x: (w: String, i: Int, v: Double) = ("hello", 5, 0.85)
print(x.w)
print(x.i)
print(x.v)

Tuple Decomposition

let x: (String, Int, Double) = ("hello", 5, 0.85)

let (word, number, value) = x //Decomposition 문법
print(word)  // hello
print(number)// 5
print(value) // 0.85

let (a, b, _) = x //_를 통해 필요 없는 멤버 생략가능

함수에서

func getSize() -> (weight: Double, height: Double) { return (250, 80)}
let x = getSize()
print("weight is \(x.weight)")
print("height is \(getSize().height)")

Tuple Matching

let resolution = (3840.0, 2160.0)

switch resolution {
	case let(w, h) where w / h == 16.0 / 9.0 :
    	// 튜블 resolution의 멤버 값을 w, h에 바인딩 하고 그 값을 통해 조건문 생성
    	print("16:9")
	case (_, 1080) : // 첫 멤버 값은 상관 없이 두번쨰 값이 1080일 경우
    	print("1080p") 
	case (3840...4096, 2160) : // 첫 멤버 값이 3840 ~ 4096
    	print("4k")
	case (3840, 2160) :
    	print("4k")
    default:
    	break
}

참조
개발자 소들이

0개의 댓글