[Swift] 2. 연산자

도윤·2021년 7월 12일
0

Swift

목록 보기
2/21

Basic Operators

기존에 사용하던 Java와의 차이점은 ..<, ... 같은 범위 연산자 제공

Comparison Opertors


(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"
("blue", -1) < ("purple", 1)        // OK, evaluates to true
("blue", false) < ("purple", true)  // Error because < can't compare Boolean values

두번의 비교를 한다는 특징이 있다.
즉 (1,"zebra") < (2,"apple") 의 경우 첫번째 값의 비교를 했을 때 1<2 가 성립하므로 true 반환.
(3, "apple") < (3, "bird")의 경우 첫번째 값이 false이지만 두번째 비교에서 사전순으로 비교하면 "apple" < "bird" 이므로 true 반환.
마지막의 ("blue", false) < ("purple", true)의 경우 true와 false는 비교가 불가능하므로 에러 발생.

Nil-Coalescing Operator

Nil-Coalescing Operator (a ?? b)는 만약 a가 value를 가지고 있다면 a의 값으로 반환하고 만약 Nil이라면 b의 값으로 반환.

b는 a와 저장된 유형이 일치해야 한다.


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는 optional String으로 선언되었고 nil이 저장되어있다.
optional type이기 때문에 Nil-Coalescing Operator을 사용할 수 있다.
nil이 저장되어있기 때문에 colorNameToUse는 defaultColorName의 값인 "red"가 저장되었다.


userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName isn't nil, so colorNameToUse is set to "green"

userDefinedColorName이 nil이 아닌 값이 저장되어 있으므로 colorNameToUse의 값도 "green"으로 저장된다.

Range Operators

closed Range Operator

(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)는 a부터 b 직전까지 b를 포함하지 않는 범위이다.
만약 a값과 b가 같다면 범위는 empty하다.
Half-Open Range는 Arrays같은 zero-base list에 유용하다.


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

한 방향으로 연속되는 범위인데, 예를 들어 index = 2에서 끝까지 Array의 모든 요소를 포함하는 범위이다.


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

0개의 댓글