티스토리 뷰

Swift & objc

typealias, Tuple

rhinoPHS 2018. 3. 16. 13:55






typealias, Tuple

- typealias : 기존 타입이나 custom타입에 별명을 붙이다.

- 보다 더 의미론적으로 코드를 작성할 수 있다.

typealias age = Int


var myAge:age = 19



-tuple : 타입들을 하나로 묶는 것

- 갯수나 타입의 제한이 없다.



let http404Error:(Int,String) = (404"Not Found")


let (statusCode, statusMessage) = http404Error

print("The status code is \(statusCode)")

// Prints "The status code is 404"

print("The status message is \(statusMessage)")

// Prints "The status message is Not Found"


// 값이 필요없으면 _ 와일드 카드를 쓰면 됩니다.

let (justTheStatusCode, _) = http404Error

print("The status code is \(justTheStatusCode)")

// Prints "The status code is 404"


// index 번호로 가져올 수 있다.

//(1,2,3,4,5,...)

print("The status code is \(http404Error.0)")

// Prints "The status code is 404"

print("The status message is \(http404Error.1)")

// Prints "The status message is Not Found"


// 혹은 이름을 줄 수도 있다.

let http200Status = (statusCode: 200, description: "OK")

print("The status code is \(http200Status.statusCode)")

// Prints "The status code is 200"

print("The status message is \(http200Status.description)")

// Prints "The status message is OK


//tuple은 함수의 멀티 리턴값으로 쓸 때 유용하다

func minMax(array: [Int]) -> (min: Int, max: Int) {

    var currentMin = array[0]

    var currentMax = array[0]

    for value in array[1..<array.count] {

        if value < currentMin {

            currentMin = value

        else if value > currentMax {

            currentMax = value

        }

    }

    return (currentMin, currentMax)

}





- tuple에 alias를 붙여주면 사용하기 편하다

var person1:(name:String, age:Int, height:Double)

var person2:(name:String, age:Int, height:Double)

var person3:(name:String, age:Int, height:Double)


typealias person = (name:String, age:Int, height:Double)


var person4:person

var person5:person

var person6:person



'Swift & objc' 카테고리의 다른 글

swift unit test  (0) 2018.03.19
피드백 정리  (0) 2018.03.19
swift type properties  (0) 2018.03.15
swift guard, if 기준정하기  (0) 2018.03.14
swift protocols  (0) 2018.03.14
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함