개발/Swift

[Swift] Typealias

Liber21 2020. 3. 12. 13:35
반응형

Typealias 란

Typealias는 기존에 존재하는 데이터 타입에 새로운 이름을 붙일 수 있는 기능이다. 
typealias가 정의되면, 프로그램에 존재하는 타입 대신 다른 이름을 사용할 수 있다. 
새로운 타입을 생성하는 것이 아닌 원래 존재하는 타입의 이름만을 바꾼다.
코드를 더 읽기 쉽고 명확하게 만든 것에 목적을 두고 있다.

즉 typealias는 수학의 치환과 같은 논리이다.

(+)
AssociatedType과 typealias는 상당히 비슷해보인다.
필자 역시 같은 고민을 겪었으나, 이 둘은 다르다고 말할 수 있다.
이 둘의 차이점을 보기전 AssociatedType을 간단하게 살펴보자.

AssociatedType는 타입을 대신(지정)해서 사용할 수 있다.
AssociatedType는 Equatable를 준수하는 곳에만 사용될 수 있으며 프로토콜에서 사용된다. 
즉, AssociatedType는 타입을 담는 곳이고, typealias는 변수를 담는 곳이라고 말할 수 있다.

 

TypeAlias를 생성하는 방법

typealias name = existing type

Swift에서 typealias는 대부분 타입에 사용할 수 있다.

  • Built-in types (String, Int, Float)
  • User-defined types (class, struct, enum)
  • Complex types (closures)

 

Built-in types의 Typealias

String, Int, Float 와 같은 데이터 타입에 사용되는 typealias

typealias Name = String

이름을 String 형태로 정의합니다. 명확한 코드를 위해 이렇게 사용할 수 있다.

let studentName : Name = "Jack"
// let studentName : String = "Jack"

아래 주석과 위의 변수는 같은 의미를 지진다.

 

 

User-defined types 의 Typealias

class, struct, enum 이 있는 User-defined types

class Student {

}

var student : Array<Student> = []

typealias 로 이렇게 바꿀 수 있다.

typealias SchoolStudent = Array<Student>

var students : SchoolStudent = []

 

 

Complex types 의 typealias

클로저에 대한 예제다. 

func method(handler:(Int) -> (String)) {

}

이 함수에 typealias를 이렇게 사용할 수 있다.

typealias CompletionHandler = (Int) -> (String)

func method(handler : CompletionHandler){

}

 

 

typealias 예시

// 학생 클래스
class Student {
    var studentName : String
    
    init(studentName : String) {
        self.studentName = studentName
    }
}

// 과목 클래스
class Subject {
    var className : String
    
    init(className: String) {
        self.className = className
    }
}


// 시간표 클래스
class TimeTable {
    var student : Student
    var subject : Subject
    
    init(student : Student, subject: Subject){
        self.student = student
        self.subject = subject
    }
}

 

활용할 typealias 를 만들어줍니다.

typealias Class = (
    student : Student,
    subject : Subject
)

 

반복해서 사용할 변수를 선언합니다.

let Jack = Student(studentName: "Jack Ripper")
let Math = Subject(className: "Math Class")

 

클래스를 사용할 경우와 typealias 를 사용한 경우

// 클래스를 사용한 경우
let FirstClass = TimeTable(student : Jack, subject: Math)
// FirstClass.student.studentName = Jack
// FirstClass.subject.className = Math

// typealias를 사용한 경우
let SecondClass = Class(Jack, Math)
// SecondClass.student.studentName = Jack
// SecondClass.subject.className = Math

 

간단 요약 : typealis는 별명이다.

 

 

Swift Typealias: How to use them and Why?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply pro

www.programiz.com

 

반응형