[Swift] 기초 - 3

팔랑이·2023년 6월 9일
post-thumbnail

23-04-20

자료형의 별칭 지정하기 (Type Aliases)

typealias 라는 키워드로 Swift에 존재하는 자료형의 별칭을 지정할 수 있다.

typealias AudioSample = UInt16

var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0



불리언 (Booleans)

참이나 거짓을 나타내는 논리형 자료형을 불리언 또는 불 이라고 한다. Swift에서는 true와 false라는 두 가지 불리언 상수값을 제공한다.

let orangesAreOrange = true
let turnipsAreDelicious = false

다음과 같이 조건문을 만들 때 유용하게 사용된다.

if turnipsAreDelicious {
    print("음 맛있다~")
} else {
    print("우웩, 맛없어")
}
// Prints "우웩, 맛없어"

Swift에서는 non-Boolean values가 불을 대체할 수 없다. 다음과 같은 경우, 컴파일 에러가 남.

let i = 1
if i{
    // this example will not compile, and will report error
}
let i = 1
if i == 1 {
    // this example will compile successfully
}



튜플(Tuples)

튜플은 여러개의 값들을 하나의 값 덩어리로 그룹을 지어준다. 어떤 자료형이든 튜플에 들어갈 수 있고, 튜플 안의 값들의 자료형이 모두 같지 않아도 된다.

다음의 예에서 (404, "Not Found")는 HTTP 상태 코드를 나타낸다.

let http404Error = (404, "Not Found")
// http404Error is of type (int, String), and ezquals (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"

인덱싱하여 값을 뽑아낼 수도 있음. 0부터 시작함. 파이썬과 달리 쉼표가 아닌 온점을 사용해 인덱싱함을 주의

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")
  • 튜플은 서로 관련된 값의 단순 그룹에 유용하고, 복잡한 데이터 구조에는 적합하지 않다. 사용하고 있는 데이터 구조가 복잡하다면, 튜플보다는 클래스나 스트럭쳐로 모델링하는 것을 추천한다.

🌏 참고사이트
Swift Language Guide

profile
정체되지 않는 성장

0개의 댓글