# Tuple

minin·2021년 10월 15일
0

Swift연습장

목록 보기
2/11

🍫 notion으로 더 재미있게 보기

* 본 포스트는 공부하며 기록용으로 작성한 포스트이기 때문에 정확하지 않은 정보가 있을 수 있습니다. 내용에 대한 피드백 환영입니다!

# Tuple

1. tuple?

  • Objective-C 에는 없었던, Swift에서 소개된 새로운 타입.
  • (val1, val2, val3)
  • 그룹 안의 값**member**들은 다양한 타입이 들어갈 수 있고, tuple 역시 멤버가 될 수 있다.` :named type, compound type, function type
  • 각 멤버들에 접근하려면 .Index 를 이용한다.
  • 각 멤버들에 대해서도 이름을 줄 수 있다.
    .element's name 으로 접근할 수 있다.
    let someTuple = (22, true, "스트링")
    someTuple.0   //22
    someTuple.1   //true
    someTuple.2   //"스트링"
    
    let otherTuple = (22, (true, "스트링"))
    otherTuple.1   //(.0 true, .1 "스트링")
    otherTuple.1.1   //"스트링"
    
    func calculateAdd() {}
    func changedMenu() {}
    let functionInTuple = (calculateAdd(), changedMenu())
    
    var userData = (height: 170, weight: 65)
    userData.height   //170
    userData.weight   //65
    
    userData.height = 180
    userData.weight = 60
    userData   //(height 180, weight 60)

  • Tuple은 함수의 return값이 될 수 있다.
    (일반적으로 이렇게, 함수로 부터 다양한 값을 반환할 때 사용된다)
    func userProfile() -> (name: String, hegiht: Int, weight: Int) {
    	return ("yooga", 170, 65)
    }
    
    userProfile()   //(name
    "yooga", hegiht 170, weight 65)

2. Tuple 주의 사항

  • tuple에 아이템을 추가하거나 지울 수 없다.
  • 한 번 선언된 tuple 멤버의 `타입`을 바꿀 수 없다.
    var userData = (height: 170, weight: 65)
    userData = (155, 50)
    userData = ("yooga", 50) // 안된다!

3. Tuple과 typealias

🔖 참고

  • typealias: 타입에 부를 대체어를 만들어 주는 것.
  typealias UserProfile = (name: String, (height: Int, weight: Int))
  var userProfile: UserProfile = ("Joe", (170, 60))

typealias를 통해서, UserProfle이라는 타입을 만들어 주었다.
→ 이렇게 타입으로 지정하면, 같은 형식(이름,키,몸무게)을 가진 여러 개의 tuple을 만들 때 유용

  var userProfiles: [UserProfile] = [("Joe", (170, 60)), ("Maz", (160, 50))]
  userProfiles.0

여기에서, userProfiles.0을 하면 Joe로 시작하는 tuple이 나올 줄 알았는데,, error가 먹는다!

왜이러지..?
이유는‼️ 내가 Array로 만들었기 때문에....(넘 당연)
그렇다면 Joe가 멤버로 있는 인덱스 0의 tuple에 접근하기 위해서는,

  userProfiles[0] // 배열에 먼저 접근을 해 주어야 한다.: (name "Joe", (height 170, weight 60))
  userProfiles[0].0 // tuple의 첫 번째 멤버인 "Joe"에 접근할 수 있다. : "Joe"

4. Tuple을 이용한 함수 예시

🔖 참고

  func split(name: String) -> (firstName: String, lastName: String) {
      let split = name.components(separatedBy: " ")
      return (split[0], split[1])
  }

  let parts = split(name: "Paul Hudson")
  parts.0
  parts.1
  parts.firstName
  parts.lastName

🔖 참고

profile
🍫 iOS 🍫 Swift

0개의 댓글