Swift 학습-Swift 기초 상해(5)

지난번 책에서 말하기를 회상회상 기본적인 데이터 유형
다음은 우리 고급스러운 것을 주문합시다.
Tuples 모듈
모듈은 한 쌍의 키 값을 저장하고 유형 제한이 없습니다
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
책에는 쓸데없는 말이 한 무더기 있다. 어쨌든 원조는 이렇게 썼다. 위의 예는 (Int,String) 유형의 원조이고 원조 안의 유형은 네가 마음대로 정의한다.
또한 원조의 변수를 분리할 수 있다.
let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
// prints "The status code is 404"
println("The status message is \(statusMessage)")
// prints "The status message is Not Found
만약 원조의 일부 값만 필요하다면 밑줄을 사용하여 필요하지 않은 값을 대체할 수 있다.
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404
인덱스를 사용하여 모듈의 값을 얻을 수도 있습니다.
println("The status code is \(http404Error.0)")
// prints "The status code is 404"
println("The status message is \(http404Error.1)")
// prints "The status message is Not Found
원조를 정의할 때 원조의 값을 명명할 수 있다. 그러면 값의 이름으로 값을 얻을 수 있다.
let http200Status = (statusCode: 200, description: "OK")

println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK
맞다. 원조의 가장 유용한 점은 함수로 되돌아갈 수 있는 값이다. 앞에서 설명한 바와 같이 Swift의 함수는 여러 개의 되돌아갈 수 있다.
그리고 원조는 복잡한 데이터 조합에 적합하지 않으니 데이터가 너무 복잡하면 클래스나 구조체를 사용하자.

좋은 웹페이지 즐겨찾기