Post

Day 26 - TIL

심화주차 과제 구현하기! + Comparable 제약조건

Day 26 - TIL

📘 Day 26 - Today I Learned

🔍 Today’s Error or Issue

1
2
3
`Value of type 'T' has no member 'sort'`

`Binary operator '<' cannot be applied to two 'T' operands`

Swift에서 제네릭 타입을 가진 구조체 내에서 sort()를 사용하려고 할 때, 타입 TComparable을 따르지 않으면 위와 같은 에러가 발생한다.

🛠️ Troubleshooting

  • TComparable을 채택한 경우에만 정렬 메서드가 동작하도록 제약 조건을 걸었다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct SortableBox<T> {
    var items: [T]
    
    mutating func sortItems() where T: Comparable {
        items.sort()
    }
}

struct Person {
    let name: String
}

var box = SortableBox(items: [Person(name: "A"), Person(name: "B")])
box.sortItems() // ❌ 에러 발생


struct Person: Comparable {
    let name: String

    static func < (lhs: Person, rhs: Person) -> Bool {
        lhs.name < rhs.name
    }
}

📝 Learning Summary

  • Swift에서 제네릭을 사용할 때, 특정 기능을 이용하려면 타입 제약(where T: Protocol)을 설정해야 함
  • Comparable을 따르지 않으면 <, sort() 같은 기능은 사용할 수 없다
  • “속성은 비교 가능해도 구조체는 그렇지 않다” → 비교 기준을 명시적으로 정의해야 함

📘 Lesson Learned

제네릭을 활용할 때, 타입이 어떤 동작을 수행할 수 있는지를 Swift는 컴파일 타임에 보장하려 한다. 따라서 정렬처럼 비교 연산이 필요한 작업은 반드시 Comparable을 통해 명시해야 함을 배웠다. 앞으로 커스텀 타입을 만들 때는 반드시 어떤 프로토콜을 채택해야 할지 고민하면서 설계하자.

This post is licensed under CC BY 4.0 by the author.