Swift 기본 연산자(Basic Operators)

이재원·7일 전
0

Swift

목록 보기
2/4

기본 연산자(Basic Operators)

산술 연산자

나머지 연산자(Remainder Operator)

나머지 연산자(a % b)는 a안에 들어갈 b의 배수가 몇인지를 계산하고 남은 값을 반환하는데, 아래 그림과 같은 방식으로 작동합니다.

이렇듯 9안에 얼마나 많은 4가 들어가는지를 통해 나머지를 구합니다.

비교 연산자(Comparison Operators)

튜플 비교

같은 타입과 같은 갯수의 값을 가지고 있는 2개의 튜플은 비교할 수 없습니다. 튜플은 2개의 값이 다를 때까지 왼쪽에서 오른쪽으로 한번에 하나씩 비교합니다. 두개의 값이 비교되고 해당 비교 결과에 따라 튜플 비교의 전체 결과가 결정됩니다.

(1, "zebra") < (2, "apple")   // true because 1 is less than 2; "zebra" and "apple" are not compared
(3, "apple") < (3, "bird")    // true because 3 is equal to 3, and "apple" is less than "bird"
(4, "dog") == (4, "dog")      // true because 4 is equal to 4, and "dog" is equal to "dog"
(4, "bird") < (4, "apple")    // false

예제 첫번째 줄처럼 튜플의 다른 어떤값과 상관없이 1이 2보다 작기 때문에 zebra가 apple보다 크더라도 true가 반환되는 것을 볼 수 있습니다. 그러나 튜플의 첫번째 요소가 같다면 두번째 요소를 비교하여 값을 반환합니다.

튜플은 각 값에 연산자를 적용할 수 있을 때만 비교 가능합니다. 따라서 Bool 타입이 포함된 튜플은 비교가 불가능 합니다.

Nil - 결합 연산자(Nil-Coalescing Operator)

nil-결합 연산자(a ?? b)는 옵셔널 a에 값이 있으면 a를 풀고, a가 nil이면 기본값인 b를 반환합니다. a와 b는 같은 타입이어야 합니다.

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

userDefinedColorName에 nil이 아닌 값을 대입하고 수행하면 userDefinedColorName에 래핑된 값을 사용합니다.

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is not nil, so colorNameToUse is set to "green"

범위 연산자(Range Operators)

닫힌 범위 연산자(Closed Range Operator)

닫힌 범위 연산자(a...b)는 값 a와 b가 포함된 a부터 b까지의 범위 실행을 정의합니다.(a < b)

for index in 1...5 {
    print("\\(index) times 5 is \\(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

반-열림 범위 연산자(Half-Open Range Operator)

반 열림 연산자(a..<b)는 b가 포함되지 않은 a부터 b-1까지의 범위 실행을 정의합니다.

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \\(i + 1) is called \\(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

단-방향 범위(One-Sided Ranges)

닫힌 범위 연산자는 한방향으로 계속되는 범위에 대한 대체 형식입니다.

for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian

반-열림 연산자 또한 마지막 값만 기입하여 단-방향 형식을 가질 수 있습니다. 보통 형식과 같이 마지막 값은 범위에 포함되지 않습니다.

for name in names[..<2] {
    print(name)
}
// Anna
// Alex

반복의 시작점이 명확하지 않은 경우 아래와 같은 방법으로도 사용할 수 있습니다.

let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

출처
이 글은 swift 공식 문서를 읽고 정리한 내용입니다.
https://bbiguduk.gitbook.io/swift/language-guide-1/basic-operators

profile
20학번 새내기^^(였음..)

0개의 댓글