본문 바로가기
FE 공부/Swift

Swift _ Generics

by 꼬질꼬질두부 2022. 10. 11.
- 형식에 의존하지 않는 범용 코드를 작성할 수 있음
- 코드의 재사용성과 유지 보수의 편의성이 높아짐

 

func name<T>(parameters) -> Type {
	code
}
//Type parameter는 문맥에 따라 실제 형식으로 대체되는 placeholder

//예제

func swapInteger(lhs: inout Int, rhs: inout Int) {
   let tmp = lhs
   lhs = rhs
   rhs = tmp
}

var a = 10
var b = 20

swapInteger(lhs: &a, rhs: &b)
a
b

// Int가 아닌 다른 형식을 교차하는 함수가 필요하면 아래처럼 하나씩 구현해야함
//하지만 함수가 중복됨
func swapInteger16(lhs: inout Int16, rhs: inout Int16) {
   // ...
}

func swapInteger64(lhs: inout Int64, rhs: inout Int64) {
   // ...
}

func swapDouble(lhs: inout Double, rhs: inout Double) {
   // ...
}


// 위의 함수를 Generic Function으로 바꿈

func swapValue<T>(lhs: inout T, rhs: inout T) {
   let tmp = lhs
   lhs = rhs
   rhs = tmp
}

Type Constraints_형식 제약

특정 클래스의 하위 클래스나, 특정 프로토콜을 준수하는 타입만 받을 수 있게 제약하는 것
<TypeParameter: ClassName>
//Typeparameter가 대체할 수 있는 형식이 class와 class를 상속한 형식으로 제약됨
<TypeParameter: ProtocolName>
//protocol을 채용한 형식으로 제약됨

 

Generic Types

구조체, 클래스, 열거형 타입에 선언하는 Generic
class Name<T>{
	code
}

struct Name<T>{
	code
}

enum Name<T>{
	code
}

struct Color<T>{
	var red: T
    var green: T
    var blue: T
}

var c = Color(red: 128, green: 80, blue: 200)//Int형으로 추론
//c = Color(red: 128.0, green: 80.0, blue: 200.0)
//let d: Color = Color(red: 128.0, green: 80.0, blue: 200.0)

 

'FE 공부 > Swift' 카테고리의 다른 글

Swift _ Stepper  (0) 2022.11.15
Swift _ Switch button  (0) 2022.11.15
Swift _ Protocols  (0) 2022.10.11
Swift _ Extensions  (0) 2022.10.11
Swift _ Method & Subscript  (0) 2022.10.10

댓글