SlideShare a Scribd company logo
1 of 18
Download to read offline
SWIFT
Operator
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Basic Operators
•Assignment Operator
•Arithmetic Operators
•Comparison Operators
•Logical Operators
•Range Operators
•Other Operators
•References
Basic Operators
Swift에서도 다른 언어들처럼 다양한 타입의 연산자를 제공합니
다. 지원하는 연산자는 아래와 같습니다.
1) 할당 연산자
2) 산술 연산자
3) 비교 연산자
4) 논리 연산자
5) 범위 연산자
6) 삼항 조건 연산자
7) Nil 병합 연산자
출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
Basic Operators
또한 연산자는 대상에 수에 따라서 아래와 같이 분류할 수 있습니
다.
1) 단항 연산자
-a, !b, c!와 같이 대상 앞뒤에 바로 붙여서 사용하는 연산자
2) 이항 연산자
2 + 3 과 같이 두 대상 사이에 위치하는 연산자
3) 삼항 연산자
a ? b : c 형태로 참과 거짓에 대한 조건을 나타내는 연산자
Swift에서는 제공하는 삼항 연산자는 위 형태 하나만 존재
출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
Assignment Operator
할당 연산자는 값을 초기화하거나 변경할 때 사용합니다.
아래와 같이 상수, 변수 모두 사용 가능합니다.
let b = 10
var a = 5
a = b // a 값은 10
let (x, y) = (1, 2) // x 는 1, y 값은 2 가 됩니다.
print("x : (x), y : (y)") // x : 1, y : 2
if x = y {
// x = y 는 값을 반환하지 않기 때문에 이 문법은 올바르지 않습니다.
}
Arithmetic Operators
사칙 연산자는 덧셈(+), 뺄셈(-), 곱셉(*), 나눗셈(/) 등에서 사용하는 연산자입
니다.
1 + 2 // 3
5 - 3 // 2
2 * 3 // 6
10.0 / 2.5 // 4.0
// 아래와 같이 나머지 연산자를 사용할 수 있습니다.
9 % 4 // 1
-9 % 4 // -1
// 단항 음수 연산자(Unary Minus Operator)
let three = 3
let minusThree = -three // minusThree는 -3
let plusThree = -minusThree // plusThree는 3, 혹은 "minus minus 3"
// 단항 양수 연산자(Unary Plus Operator)
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix는 -6
// 합성 할당 연산자 (Compound Assignment Operators)
var a = 1
a += 2 // a는 3
// 덧셈 연산을 통하여 문자를 합칠 수 있습니다.
"hello, " + "world" // equals "hello, world"
Comparison Operators
Swift에서는 비교를 위한 비교 연산자로서 아래와 같은 연산자를
지원합니다.
1) 같다 (a == b)
2) 같지않다 (a != b)
3) 크다 (a > b)
4) 작다 (a < b)
5) 크거나 같다 (a >= b)
6) 작거나 같다 (a <= b)
1 == 1 // true
2 != 1 // true
2 > 1 // true
1 < 2 // true
1 >= 1 // true
2 <= 1 // false
Comparison Operators
let name = "world"
// if-else 조건 구문에서도 비교 연산을 할 수 있다.
if name == "world" {
print("hello, world")
} else {
print("I'm sorry (name), but I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".
(1, "zebra") < (2, "apple") // true, 1이 2보다 작고; zebra가 apple은 비교하지 않기 때문
(3, "apple") < (3, "bird") // true 왼쪽 3이 오른쪽 3과 같고; apple은 bird보다 작기 때문
(4, "dog") == (4, "dog") // true 왼쪽 4는 오른쪽 4와 같고 왼쪽 dog는 오른쪽 dog와 같기 때문
("blue", -1) < ("purple", 1) // 비교가능, 결과 : true
("blue", false) < ("purple", true) // 에러, Boolean 값은 < 연산자로 비교할 수 없다.
Logical Operators
Swift에서는 세가지 표준 논리 연산자를 지원합니다.
1) 논리 부정 NOT ( !a )
2) 논리 곱 AND ( a && b)
3) 논리 합 ( a || b )
Logical Operators
// 논리 부정 연산자(Logical NOT Operator)
let allowedEntry = false
if !allowedEntry {
print("ACCESS DENIED")
} // Prints "ACCESS DENIED"
// 논리 곱 연산자(Logical AND Operator)
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
print("Welcome!")
} else {
print("ACCESS DENIED")
} // Prints "ACCESS DENIED"
// 논리 합(OR) 연산자(Logical OR Operator)
let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
} // Prints "Welcome!"
Logical Operators
let enteredDoorCode = true
let passedRetinaScan = false
let hasDoorKey = false
let knowsOverridePassword = true
// 논리 연산자의 조합(Combining Logical Operators)
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
} // Prints "Welcome!"
// 명시적 괄호(Explicit Parentheses)
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
} // Prints "Welcome!"
Range Operators
Swift에서 지원하는 특별한 연산자로서 특정 범위에 대해서 지정할 수 있는
범위 연산자입니다.
// 닫힌 범위 연산자(Closed Range Operator)
// (a..b)의 형태로 범위의 시작과 끝이 있는 연산자 입니다. for-in loop에 자주 사용됩니다.
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보다 작을 때까지의 범위를 갖습니다. 즉, 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
Range Operators
// 단방향 범위(One-Side Ranges)
// [a..] [..a]의 형태로 범위의 시작 혹은 끝만 지정해 사용하는 범위 연산자 입니다.
let names = ["Anna", "Alex", "Brian", "Jack"]
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
// 단방향 범위 연산자는 subscript뿐만 아니라 아래와 같이 특정 값을 포함하는지 여부를 확인할 때도 사용 가능합니다.
let range = ...5
print(range.contains(7)) // false
print(range.contains(4)) // true
print(range.contains(-1)) // true
Other Operators
삼항 조건 연산자(Ternary Conditional Operator)
// 삼항 조건 연산자는 question ? answer1 : answer2의 구조를 갖습니다.
// question 조건이 참인경우 answer1이 거짓인 경우 answer2가 실행됩니다.
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
print(rowHeight) // rowHeight는 90 (40 + 50)
// 위에서 삼항 조건 연산을 아래과 같이 풀어 쓸 수 있습니다.
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
} // rowHeight는 90입니다.
Other Operators
Nil 병합 연산자(Nil-Coalescing Operator)
// nil 병합 연산자는 a ?? b 형태를 갖는 연산자 입니다.
// 옵셔널 a를 벗겨서(unwraps) 만약 a가 nil 인 경우 b를 반환합니다.
// 사용 예) a != nil ? a! : b
let defaultColorName = "red"
var userDefinedColorName: String? // 이 값은 defaults 값 nil입니다.
var colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse) // red
// userDefinedColorNam이 nil이므로 colorNameToUse 값은 defaultColorName인 "red"가 설정
됩니다.
userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse) // green
// userDefinedColorName가 nil이 아니므로 colorNameToUse 는 "green"이 됩니다.
References
[1] 기본 연산자 (Basic Operators) : https://jusung.gitbook.io/
the-swift-language-guide/language-guide/02-basic-operators
[2] [Swift]Basic Operators 정리 : http://minsone.github.io/
mac/ios/swift-basic-operators-summary
[3] Swift 5.2: Basic Operators (기본 연산자) : https://
xho95.github.io/swift/language/grammar/basic/operators/
2016/04/27/Basic-Operators.html
[4] Basic Operators : https://docs.swift.org/swift-book/
LanguageGuide/BasicOperators.html
[5] 오늘의 Swift 상식 (Custom Operator, Generic) : https://
medium.com/@jgj455/오늘의-swift-상식-custom-operator-
generic-58e783742b
References
[6] Swift Operators : https://www.programiz.com/swift-
programming/operators
[7] 범위 연산자 (Range Operators) : https://m.blog.naver.com/
PostView.nhn?
blogId=badwin&logNo=221177227872&proxyReferer=https:
%2F%2Fwww.google.com%2F
[8] Swift - Operators : https://www.tutorialspoint.com/swift/
swift_operators.htm
[9] Operator Declarations : https://developer.apple.com/
documentation/swift/swift_standard_library/
operator_declarations
[10] (Swift) 스위프트 연산자(Operator) 기초 : https://
googry.tistory.com/37
Thank you!

More Related Content

What's hot

자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초진수 정
 
Swift basic operators-controlflow
Swift basic operators-controlflowSwift basic operators-controlflow
Swift basic operators-controlflowwileychoi
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdfHyosang Hong
 
PHP 함수와 제어구조
PHP 함수와 제어구조PHP 함수와 제어구조
PHP 함수와 제어구조Yoonwhan Lee
 
Python if loop-function
Python if loop-functionPython if loop-function
Python if loop-function건희 김
 
0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)Sung-hoon Ma
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] FunctionsBill Kim
 
RPG Maker와 Ruby로 코딩 시작하기 Day 3
RPG Maker와 Ruby로 코딩 시작하기 Day 3RPG Maker와 Ruby로 코딩 시작하기 Day 3
RPG Maker와 Ruby로 코딩 시작하기 Day 3Sunwoo Park
 
1.Startup JavaScript - 프로그래밍 기초
1.Startup JavaScript - 프로그래밍 기초1.Startup JavaScript - 프로그래밍 기초
1.Startup JavaScript - 프로그래밍 기초Circulus
 

What's hot (12)

자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초
 
php 시작하기
php 시작하기php 시작하기
php 시작하기
 
PHP 기초 문법
PHP 기초 문법PHP 기초 문법
PHP 기초 문법
 
Perl Script
Perl ScriptPerl Script
Perl Script
 
Swift basic operators-controlflow
Swift basic operators-controlflowSwift basic operators-controlflow
Swift basic operators-controlflow
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdf
 
PHP 함수와 제어구조
PHP 함수와 제어구조PHP 함수와 제어구조
PHP 함수와 제어구조
 
Python if loop-function
Python if loop-functionPython if loop-function
Python if loop-function
 
0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
RPG Maker와 Ruby로 코딩 시작하기 Day 3
RPG Maker와 Ruby로 코딩 시작하기 Day 3RPG Maker와 Ruby로 코딩 시작하기 Day 3
RPG Maker와 Ruby로 코딩 시작하기 Day 3
 
1.Startup JavaScript - 프로그래밍 기초
1.Startup JavaScript - 프로그래밍 기초1.Startup JavaScript - 프로그래밍 기초
1.Startup JavaScript - 프로그래밍 기초
 

Similar to [Swift] Operator

Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자Park Jonggun
 
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수Aiden Seonghak Hong
 
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩해강
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.Young-Beom Rhee
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자Circulus
 
R 기초 : R Basics
R 기초 : R BasicsR 기초 : R Basics
R 기초 : R BasicsYoonwhan Lee
 
Javascript 1
Javascript 1Javascript 1
Javascript 1swmin
 
Angular2 가기전 Type script소개
 Angular2 가기전 Type script소개 Angular2 가기전 Type script소개
Angular2 가기전 Type script소개Dong Jun Kwon
 
스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오Taeoh Kim
 
Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Yong Joon Moon
 
파이썬 기초
파이썬 기초 파이썬 기초
파이썬 기초 Yong Joon Moon
 
0327.web&ruby&rails
0327.web&ruby&rails0327.web&ruby&rails
0327.web&ruby&rails민정 김
 
C Language I
C Language IC Language I
C Language ISuho Kwon
 

Similar to [Swift] Operator (16)

Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자
 
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수
RHive tutorial 4: RHive 튜토리얼 4 - UDF, UDTF, UDAF 함수
 
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자
 
R 기초 : R Basics
R 기초 : R BasicsR 기초 : R Basics
R 기초 : R Basics
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
7장매크로
7장매크로7장매크로
7장매크로
 
Javascript 1
Javascript 1Javascript 1
Javascript 1
 
Angular2 가기전 Type script소개
 Angular2 가기전 Type script소개 Angular2 가기전 Type script소개
Angular2 가기전 Type script소개
 
스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오
 
Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713
 
파이썬 기초
파이썬 기초 파이썬 기초
파이썬 기초
 
0327.web&ruby&rails
0327.web&ruby&rails0327.web&ruby&rails
0327.web&ruby&rails
 
06장 함수
06장 함수06장 함수
06장 함수
 
C Language I
C Language IC Language I
C Language I
 

More from Bill Kim

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting ComparisonBill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O NotationBill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell SortBill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix SortBill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick SortBill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap SortBill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting SortBill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection SortBill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge SortBill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion SortBill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble SortBill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary SearchBill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)Bill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVLBill Kim
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search TreeBill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)Bill Kim
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary TreeBill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - TreeBill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - GraphBill Kim
 

More from Bill Kim (20)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O Notation
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell Sort
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix Sort
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick Sort
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap Sort
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting Sort
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection Sort
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge Sort
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary Search
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
 

[Swift] Operator

  • 2. 목차 •Basic Operators •Assignment Operator •Arithmetic Operators •Comparison Operators •Logical Operators •Range Operators •Other Operators •References
  • 3. Basic Operators Swift에서도 다른 언어들처럼 다양한 타입의 연산자를 제공합니 다. 지원하는 연산자는 아래와 같습니다. 1) 할당 연산자 2) 산술 연산자 3) 비교 연산자 4) 논리 연산자 5) 범위 연산자 6) 삼항 조건 연산자 7) Nil 병합 연산자 출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
  • 4. Basic Operators 또한 연산자는 대상에 수에 따라서 아래와 같이 분류할 수 있습니 다. 1) 단항 연산자 -a, !b, c!와 같이 대상 앞뒤에 바로 붙여서 사용하는 연산자 2) 이항 연산자 2 + 3 과 같이 두 대상 사이에 위치하는 연산자 3) 삼항 연산자 a ? b : c 형태로 참과 거짓에 대한 조건을 나타내는 연산자 Swift에서는 제공하는 삼항 연산자는 위 형태 하나만 존재 출처: https://noahlogs.tistory.com/13 [인생의 로그캣]
  • 5. Assignment Operator 할당 연산자는 값을 초기화하거나 변경할 때 사용합니다. 아래와 같이 상수, 변수 모두 사용 가능합니다. let b = 10 var a = 5 a = b // a 값은 10 let (x, y) = (1, 2) // x 는 1, y 값은 2 가 됩니다. print("x : (x), y : (y)") // x : 1, y : 2 if x = y { // x = y 는 값을 반환하지 않기 때문에 이 문법은 올바르지 않습니다. }
  • 6. Arithmetic Operators 사칙 연산자는 덧셈(+), 뺄셈(-), 곱셉(*), 나눗셈(/) 등에서 사용하는 연산자입 니다. 1 + 2 // 3 5 - 3 // 2 2 * 3 // 6 10.0 / 2.5 // 4.0 // 아래와 같이 나머지 연산자를 사용할 수 있습니다. 9 % 4 // 1 -9 % 4 // -1 // 단항 음수 연산자(Unary Minus Operator) let three = 3 let minusThree = -three // minusThree는 -3 let plusThree = -minusThree // plusThree는 3, 혹은 "minus minus 3" // 단항 양수 연산자(Unary Plus Operator) let minusSix = -6 let alsoMinusSix = +minusSix // alsoMinusSix는 -6 // 합성 할당 연산자 (Compound Assignment Operators) var a = 1 a += 2 // a는 3 // 덧셈 연산을 통하여 문자를 합칠 수 있습니다. "hello, " + "world" // equals "hello, world"
  • 7. Comparison Operators Swift에서는 비교를 위한 비교 연산자로서 아래와 같은 연산자를 지원합니다. 1) 같다 (a == b) 2) 같지않다 (a != b) 3) 크다 (a > b) 4) 작다 (a < b) 5) 크거나 같다 (a >= b) 6) 작거나 같다 (a <= b) 1 == 1 // true 2 != 1 // true 2 > 1 // true 1 < 2 // true 1 >= 1 // true 2 <= 1 // false
  • 8. Comparison Operators let name = "world" // if-else 조건 구문에서도 비교 연산을 할 수 있다. if name == "world" { print("hello, world") } else { print("I'm sorry (name), but I don't recognize you") } // Prints "hello, world", because name is indeed equal to "world". (1, "zebra") < (2, "apple") // true, 1이 2보다 작고; zebra가 apple은 비교하지 않기 때문 (3, "apple") < (3, "bird") // true 왼쪽 3이 오른쪽 3과 같고; apple은 bird보다 작기 때문 (4, "dog") == (4, "dog") // true 왼쪽 4는 오른쪽 4와 같고 왼쪽 dog는 오른쪽 dog와 같기 때문 ("blue", -1) < ("purple", 1) // 비교가능, 결과 : true ("blue", false) < ("purple", true) // 에러, Boolean 값은 < 연산자로 비교할 수 없다.
  • 9. Logical Operators Swift에서는 세가지 표준 논리 연산자를 지원합니다. 1) 논리 부정 NOT ( !a ) 2) 논리 곱 AND ( a && b) 3) 논리 합 ( a || b )
  • 10. Logical Operators // 논리 부정 연산자(Logical NOT Operator) let allowedEntry = false if !allowedEntry { print("ACCESS DENIED") } // Prints "ACCESS DENIED" // 논리 곱 연산자(Logical AND Operator) let enteredDoorCode = true let passedRetinaScan = false if enteredDoorCode && passedRetinaScan { print("Welcome!") } else { print("ACCESS DENIED") } // Prints "ACCESS DENIED" // 논리 합(OR) 연산자(Logical OR Operator) let hasDoorKey = false let knowsOverridePassword = true if hasDoorKey || knowsOverridePassword { print("Welcome!") } else { print("ACCESS DENIED") } // Prints "Welcome!"
  • 11. Logical Operators let enteredDoorCode = true let passedRetinaScan = false let hasDoorKey = false let knowsOverridePassword = true // 논리 연산자의 조합(Combining Logical Operators) if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword { print("Welcome!") } else { print("ACCESS DENIED") } // Prints "Welcome!" // 명시적 괄호(Explicit Parentheses) if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword { print("Welcome!") } else { print("ACCESS DENIED") } // Prints "Welcome!"
  • 12. Range Operators Swift에서 지원하는 특별한 연산자로서 특정 범위에 대해서 지정할 수 있는 범위 연산자입니다. // 닫힌 범위 연산자(Closed Range Operator) // (a..b)의 형태로 범위의 시작과 끝이 있는 연산자 입니다. for-in loop에 자주 사용됩니다. 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보다 작을 때까지의 범위를 갖습니다. 즉, 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
  • 13. Range Operators // 단방향 범위(One-Side Ranges) // [a..] [..a]의 형태로 범위의 시작 혹은 끝만 지정해 사용하는 범위 연산자 입니다. let names = ["Anna", "Alex", "Brian", "Jack"] 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 // 단방향 범위 연산자는 subscript뿐만 아니라 아래와 같이 특정 값을 포함하는지 여부를 확인할 때도 사용 가능합니다. let range = ...5 print(range.contains(7)) // false print(range.contains(4)) // true print(range.contains(-1)) // true
  • 14. Other Operators 삼항 조건 연산자(Ternary Conditional Operator) // 삼항 조건 연산자는 question ? answer1 : answer2의 구조를 갖습니다. // question 조건이 참인경우 answer1이 거짓인 경우 answer2가 실행됩니다. let contentHeight = 40 let hasHeader = true let rowHeight = contentHeight + (hasHeader ? 50 : 20) print(rowHeight) // rowHeight는 90 (40 + 50) // 위에서 삼항 조건 연산을 아래과 같이 풀어 쓸 수 있습니다. let contentHeight = 40 let hasHeader = true let rowHeight: Int if hasHeader { rowHeight = contentHeight + 50 } else { rowHeight = contentHeight + 20 } // rowHeight는 90입니다.
  • 15. Other Operators Nil 병합 연산자(Nil-Coalescing Operator) // nil 병합 연산자는 a ?? b 형태를 갖는 연산자 입니다. // 옵셔널 a를 벗겨서(unwraps) 만약 a가 nil 인 경우 b를 반환합니다. // 사용 예) a != nil ? a! : b let defaultColorName = "red" var userDefinedColorName: String? // 이 값은 defaults 값 nil입니다. var colorNameToUse = userDefinedColorName ?? defaultColorName print(colorNameToUse) // red // userDefinedColorNam이 nil이므로 colorNameToUse 값은 defaultColorName인 "red"가 설정 됩니다. userDefinedColorName = "green" colorNameToUse = userDefinedColorName ?? defaultColorName print(colorNameToUse) // green // userDefinedColorName가 nil이 아니므로 colorNameToUse 는 "green"이 됩니다.
  • 16. References [1] 기본 연산자 (Basic Operators) : https://jusung.gitbook.io/ the-swift-language-guide/language-guide/02-basic-operators [2] [Swift]Basic Operators 정리 : http://minsone.github.io/ mac/ios/swift-basic-operators-summary [3] Swift 5.2: Basic Operators (기본 연산자) : https:// xho95.github.io/swift/language/grammar/basic/operators/ 2016/04/27/Basic-Operators.html [4] Basic Operators : https://docs.swift.org/swift-book/ LanguageGuide/BasicOperators.html [5] 오늘의 Swift 상식 (Custom Operator, Generic) : https:// medium.com/@jgj455/오늘의-swift-상식-custom-operator- generic-58e783742b
  • 17. References [6] Swift Operators : https://www.programiz.com/swift- programming/operators [7] 범위 연산자 (Range Operators) : https://m.blog.naver.com/ PostView.nhn? blogId=badwin&logNo=221177227872&proxyReferer=https: %2F%2Fwww.google.com%2F [8] Swift - Operators : https://www.tutorialspoint.com/swift/ swift_operators.htm [9] Operator Declarations : https://developer.apple.com/ documentation/swift/swift_standard_library/ operator_declarations [10] (Swift) 스위프트 연산자(Operator) 기초 : https:// googry.tistory.com/37