Swift 공식문서(2) - Basic Operators

Jiyoon·2022년 3월 19일
0

iOS

목록 보기
6/16
post-thumbnail

Remainder Operator

-9 % 4   // equals -1
9 % -4 //equals 1

나누는 값이 음수일 경우, 절댓값으로 생각하고 계산한다

Comparison Operators

같은 타입과 같은 갯수의 값을 가진다며 튜플끼리도 비교할 수 있다

(1, "zebra") < (2, "apple")   // true because 1 is less than 2; "zebra" and "apple" aren't 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"

부등호를 이용한 비교연산에서는 첫번째 값들로 충족되면 더이상 비교하지 않는다만약 같다면, 뒤 인자도 비교.

문자열끼리의 비교는 사전순으로 비교된다!

Ternary Conditional Operator

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

question ? answer1 : answer2 → true면 answer1, false면 answer2

ternary conditional operator를 너무 무분별하게 쓰면 읽기 어려운 코드가 되므로 조심해서 써야한다.

또한, 하나의 statement에서 여러개의 ternary conditonal operator를 쓰는 것을 피해라.

Nil-Coalescing Operator

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"

nil값이면 colorNameToUse에 default로 정해준 값이 들어가고 아니면 userDefined값이 들어간다

Range Operators

//닫힌 구간
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count

//한쪽만 닫힌 구간
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
for name in names[2...] {
    print(name)
}
let range = ...5

0개의 댓글