SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
송치원 (곰튀김)
iamchiwon.github.io
Custom Operators
in Swift
Realism Programmer
Operators
basic
Basic Operators
// Assignment Operator
var num = 40
// Compound Assignment Operator
num += 2
// Arithmetic Operators
40 + 2
44 - 2
21 * 2
84 / 2
// Remainder Operators
42 % 3
// Unary (Plus/Minus) Operator
let minusNum = -num
let plusNum = +num
// Comparison Operators
minusNum == plusNum
minusNum != plusNum
minusNum > plusNum
minusNum >= plusNum
minusNum < plusNum
minusNum <= plusNum
// Logical Operators
!true
true && true
true || false
https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html
Q.
2 + 2 * 2 == 8
의 결과는?
① true ② false
Not-Support Operators
let hello = "Hello"
let world = "World"
let greeting = hello + world
let noL = greeting - "l"
let world5 = world * 5
greeting[-1] == "d"
hello[1 ... 4] == "ello"
Binary operator '-' cannot be applied to two 'String' operands
Binary operator '*' cannot be applied to operands of type 'String' and 'Int'
'subscript(_:)' is unavailable: cannot subscript String with an Int, see the…
'subscript(_:)' is unavailable: cannot subscript String with an integer range, see …
Customize Operators
1.Overload
2.Extension
3.Customize Operators
hello[1 ... 4] == "ello"
greeting[-1] == "d"
let world5 = world * 5
let noL = greeting - "l"
Operators Overload
let hello = "Hello"
let world = "World"
let greeting = hello + world
let noL = greeting - "l" // HeoWord
let world5 = world * 5 // WorldWorldWorldWorldWorld
let text = greeting - "," - " " + "!" * 2 // HelloWorld!!
func - (_ origin: String, _ removal: String) -> String {
return origin.replacingOccurrences(of: removal, with: "")
}
func * (_ origin: String, _ times: Int) -> String {
return Array(1 ... times).map { _ in origin }.reduce("", +)
}
Extensions
let hello = "Hello"
let world = "World"
let greeting = hello + world
greeting[3] // "l"
greeting[-1] // "d"
extension String {
subscript(i: Int) -> Character {
var offset = i
while offset < 0 { offset += count }
let index = self.index(startIndex, offsetBy: offset)
return self[index]
}
}
Extensions
let hello = "Hello"
let world = "World"
let greeting = hello + world
hello[1 ... 4] // "ello"
hello[1 ..< 4] // "ell"
extension String {
subscript(_ range: CountableClosedRange<Int>) -> Substring {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = index(self.startIndex, offsetBy: range.upperBound)
return self[startIndex ... endIndex]
}
subscript(_ r: CountableRange<Int>) -> Substring {
let startIndex = index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex ..< endIndex]
}
}
Operators
custom
Custom Operator
let gray = UIView()
gray.translatesAutoresizingMaskIntoConstraints = false
gray.backgroundColor = .systemGray
view.addSubview(gray)
gray ~> view
infix operator ~>: LogicalDisjunctionPrecedence
@discardableResult
func ~> (left: UIView,
right: UIView) -> UIView {
left.topAnchor.constraint(equalTo: right.topAnchor).isActive = true
left.leftAnchor.constraint(equalTo: right.leftAnchor).isActive = true
left.rightAnchor.constraint(equalTo: right.rightAnchor).isActive = true
left.bottomAnchor.constraint(equalTo: right.bottomAnchor).isActive = true
return left
}
Precedence Groups
Group Name Associativity Example Priority
BitwiseShiftPrecedence none << >>
Higher
Lower
MultiplicationPrecedence left * /
AdditionPrecedence left + -
RangeFormationPrecedence none … ..<
CastingPrecedence none as
NilCoalescingPrecedence right ??
ComparisonPrecedence none < <= > >= ==
LogicalConjunctionPrecedence left &&
LogicalDisjunctionPrecedence left ||
TernaryPrecedence right ? :
AssignmentPrecedence right += = *= -= /=
https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations
Custom Operator
let green = UIView()
green.translatesAutoresizingMaskIntoConstraints = false
green.backgroundColor = .systemGreen
view.addSubview(green)
green.topAnchor ~> view.topAnchor + 50
green.centerXAnchor ~> view.centerXAnchor
green.widthAnchor ~> 300
green.heightAnchor ~> 200
@discardableResult
func ~> (left: NSLayoutXAxisAnchor,
right: NSLayoutXAxisAnchor) -> NSLayoutXAxisAnchor {
left.constraint(equalTo: right).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutDimension,
right: CGFloat) -> NSLayoutDimension {
left.constraint(equalToConstant: right).isActive = true
return left
}
Custom Operator
let green = UIView()
green.translatesAutoresizingMaskIntoConstraints = false
green.backgroundColor = .systemGreen
view.addSubview(green)
green.topAnchor ~> view.topAnchor + 50
green.centerXAnchor ~> view.centerXAnchor
green.widthAnchor ~> 300
green.heightAnchor ~> 200
@discardableResult
func ~> (left: NSLayoutXAxisAnchor,
right: (anchor: NSLayoutXAxisAnchor,
constant: CGFloat)) -> NSLayoutXAxisAnchor {
left.constraint(equalTo: right.anchor,
constant: right.constant).isActive = true
return left
}
func + (left: NSLayoutXAxisAnchor,
right: CGFloat) -> (anchor: NSLayoutXAxisAnchor,
constant: CGFloat) {
(left, right)
}
Operating on functions
func uppercased(_ text: String) -> String {
return text.uppercased()
}
func output(_ it: Any) -> Void {
print("(it)")
}
output(uppercased("Hello World")) // HELLO WORLD
func ~> <A, B, C>(_ f1: @escaping (A) -> B,
_ f2: @escaping (B) -> C) -> (A) -> C {
{ a in
f2(f1(a))
}
}
(uppercased ~> output)("Hello World") // HELLO WORLD
let upperPrinter = uppercased ~> output // (String) -> Void
upperPrinter("Hello World") // HELLO WORLD
Composition of functions
func just<T>(_ f: @escaping () -> T) -> () -> T {
{
f()
}
}
func map<T, U>(_ setter: @escaping (T) -> U) -> (T) -> U {
{ t in
return setter(t)
}
}
func output(_ it: Any) -> Void {
print("(it)")
}
output(
map({ $0.uppercased() })(
just({ "Hello World" })()
)
)
// HELLO WORLD
Composition of functions
func just<T>(_ f: @escaping () -> T) -> () -> T {
{
f()
}
}
func map<T, U>(_ setter: @escaping (T) -> U) -> (T) -> U {
{ t in
return setter(t)
}
}
func output(_ it: Any) -> Void {
print("(it)")
}
let fn = just { "Hello World" } ~> map { $0.count } ~> output
fn(())
// 11
() -> String (String) -> Int (Any) -> ()
(()) -> ()
Composition of functions
@discardableResult
func run<T>(_ f: (()) -> T) -> T {
f(())
}
run(
just { "let us: Go! 2019" }
~> map { $0.uppercased() }
~> output
)
// LET US: GO! 2019
Q.
다음 중 custom operator 로 사용할 수 있는 것은?
① infix operator ~>: AdditionPrecedence
② infix operator ->: AdditionPrecedence
③ infix operator as: AdditionPrecedence
④ infix operator $$: AdditionPrecedence
https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418
All together
readable code
run(
just { UIView() }
~> addSubView(view)
~> map { v -> UIView in
v.backgroundColor = .systemGray
v ~> self.view
return v
}
)
let green = run(
just { UIView() }
~> addSubView(view)
~> map { v -> UIView in
v.backgroundColor = .systemGreen
return v
}
~> map { v -> UIView in
v.topAnchor ~> self.view.topAnchor + 50
v.leftAnchor ~> self.view.leftAnchor + 50
v.rightAnchor ~> self.view.rightAnchor - 50
v.heightAnchor ~> 200
return v
}
)
let yellow = run(
just { UIView() }
~> addSubView(view)
~> map { v -> UIView in
v.backgroundColor = .systemYellow
return v
}
~> map { v -> UIView in
v.topAnchor ~> green.topAnchor + 100
v.centerXAnchor ~> self.view.centerXAnchor
v.widthAnchor ~> 200
v.heightAnchor ~> 200
return v
}
)
run(
just { UIView() }
~> addSubView(view)
~> map { v -> UIView in
v.backgroundColor = .systemRed
return v
}
~> map { v -> UIView in
v.centerXAnchor ~> yellow.centerXAnchor
v.centerYAnchor ~> yellow.centerYAnchor
v.widthAnchor ~> yellow.widthAnchor * 0.5
v.heightAnchor ~> yellow.heightAnchor / 2
return v
}
)
let addSubView: (UIView) -> (UIView) -> UIView = { parent in
{ v in
parent.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
return v
}
}
@discardableResult
func ~> (left: UIView,
right: UIView) -> UIView {
left.topAnchor.constraint(equalTo: right.topAnchor).isActive = true
left.leftAnchor.constraint(equalTo: right.leftAnchor).isActive = true
left.rightAnchor.constraint(equalTo: right.rightAnchor).isActive = true
left.bottomAnchor.constraint(equalTo: right.bottomAnchor).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutDimension,
right: CGFloat) -> NSLayoutDimension {
left.constraint(equalToConstant: right).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutXAxisAnchor,
right: NSLayoutXAxisAnchor) -> NSLayoutXAxisAnchor {
left.constraint(equalTo: right).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutXAxisAnchor,
right: (anchor: NSLayoutXAxisAnchor,
constant: CGFloat)) -> NSLayoutXAxisAnchor {
left.constraint(equalTo: right.anchor,
constant: right.constant).isActive = true
return left
}
func + (left: NSLayoutXAxisAnchor,
right: CGFloat) -> (anchor: NSLayoutXAxisAnchor,
constant: CGFloat) {
(left, right)
}
func - (left: NSLayoutXAxisAnchor,
right: CGFloat) -> (anchor: NSLayoutXAxisAnchor,
constant: CGFloat) {
(left, -right)
}
@discardableResult
func ~> (left: NSLayoutDimension,
right: CGFloat) -> NSLayoutDimension {
left.constraint(equalToConstant: right).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutDimension,
right: NSLayoutDimension) -> NSLayoutDimension {
left.constraint(equalTo: right, multiplier: 1).isActive = true
return left
}
@discardableResult
func ~> (left: NSLayoutDimension,
right: (anchor: NSLayoutDimension,
multiplier: CGFloat)) -> NSLayoutDimension {
left.constraint(equalTo: right.anchor,
multiplier: right.multiplier).isActive = true
return left
}
func * (left: NSLayoutDimension,
right: CGFloat) -> (anchor: NSLayoutDimension,
multiplier: CGFloat) {
(left, right)
}
func / (left: NSLayoutDimension,
right: CGFloat) -> (anchor: NSLayoutDimension,
multiplier: CGFloat) {
(left, 1 / right)
}
https://github.com/iamchiwon/CustomizeOperators
Sample Codes
Is it useful?
ObjectMapper
https://github.com/tristanhimmelman/ObjectMapper
Cartography
https://github.com/robb/Cartography
Summary
1. Operator Overloading, Extension, Custom Operator
을 활용해서 기능을 추가할 수 있다.
2. Operator는 Precedence 에 의한 연산 우선순위가 적용된다.
3. value 뿐 아니라 function 에도 연산자를 적용할 수 있다.
4. 복잡할 수 있는 연산을 간결하게 표현할 수 있다.
5. 코드의 가독성을 높일 수 있다.
( ⚠ 과하면 오히려 가독성을 해칠 수 있다 )
끝

Contenu connexe

Tendances

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with goEleanor McHugh
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterRicardo Signes
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperosfameron
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CEleanor McHugh
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVMjwausle
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)GroovyPuzzlers
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixirKent Ohashi
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoEleanor McHugh
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tiebrian d foy
 

Tendances (20)

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Yahoo! JAPANとKotlin
Yahoo! JAPANとKotlinYahoo! JAPANとKotlin
Yahoo! JAPANとKotlin
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::Exporter
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & C
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
5th Sem SS lab progs
5th Sem SS lab progs5th Sem SS lab progs
5th Sem SS lab progs
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)
 
Unix prog
Unix progUnix prog
Unix prog
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with Go
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
Camping
CampingCamping
Camping
 

Similaire à 20191116 custom operators in swift

Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix TaskHermann Hueck
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Gesh Markov
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For GoogleEleanor McHugh
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using ScalaSiarhiej Siemianchuk
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de donnéesRomain Lecomte
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnıl Sözeri
 

Similaire à 20191116 custom operators in swift (20)

Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Javascript
JavascriptJavascript
Javascript
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Plus de Chiwon Song

20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기Chiwon Song
 
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)Chiwon Song
 
20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POPChiwon Song
 
20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?Chiwon Song
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계Chiwon Song
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversionsChiwon Song
 
[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안Chiwon Song
 
[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행Chiwon Song
 
20190330 immutable data
20190330 immutable data20190330 immutable data
20190330 immutable dataChiwon Song
 
20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해Chiwon Song
 
20171104 FRP 패러다임
20171104 FRP 패러다임20171104 FRP 패러다임
20171104 FRP 패러다임Chiwon Song
 
스크래치로 시작하는 코딩
스크래치로 시작하는 코딩스크래치로 시작하는 코딩
스크래치로 시작하는 코딩Chiwon Song
 
메이커운동과 아두이노
메이커운동과 아두이노메이커운동과 아두이노
메이커운동과 아두이노Chiwon Song
 
아두이노 RC카 만들기
아두이노 RC카 만들기아두이노 RC카 만들기
아두이노 RC카 만들기Chiwon Song
 
[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoTChiwon Song
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷Chiwon Song
 
[2] 아두이노 활용 실습
[2] 아두이노 활용 실습[2] 아두이노 활용 실습
[2] 아두이노 활용 실습Chiwon Song
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노Chiwon Song
 
[1] IoT와 아두이노
[1] IoT와 아두이노[1] IoT와 아두이노
[1] IoT와 아두이노Chiwon Song
 
3D 프린터와 아두이노
3D 프린터와 아두이노3D 프린터와 아두이노
3D 프린터와 아두이노Chiwon Song
 

Plus de Chiwon Song (20)

20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기
 
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
 
20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP
 
20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversions
 
[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안
 
[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행
 
20190330 immutable data
20190330 immutable data20190330 immutable data
20190330 immutable data
 
20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해
 
20171104 FRP 패러다임
20171104 FRP 패러다임20171104 FRP 패러다임
20171104 FRP 패러다임
 
스크래치로 시작하는 코딩
스크래치로 시작하는 코딩스크래치로 시작하는 코딩
스크래치로 시작하는 코딩
 
메이커운동과 아두이노
메이커운동과 아두이노메이커운동과 아두이노
메이커운동과 아두이노
 
아두이노 RC카 만들기
아두이노 RC카 만들기아두이노 RC카 만들기
아두이노 RC카 만들기
 
[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
 
[2] 아두이노 활용 실습
[2] 아두이노 활용 실습[2] 아두이노 활용 실습
[2] 아두이노 활용 실습
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노
 
[1] IoT와 아두이노
[1] IoT와 아두이노[1] IoT와 아두이노
[1] IoT와 아두이노
 
3D 프린터와 아두이노
3D 프린터와 아두이노3D 프린터와 아두이노
3D 프린터와 아두이노
 

Dernier

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 

Dernier (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

20191116 custom operators in swift

  • 3. Basic Operators // Assignment Operator var num = 40 // Compound Assignment Operator num += 2 // Arithmetic Operators 40 + 2 44 - 2 21 * 2 84 / 2 // Remainder Operators 42 % 3 // Unary (Plus/Minus) Operator let minusNum = -num let plusNum = +num // Comparison Operators minusNum == plusNum minusNum != plusNum minusNum > plusNum minusNum >= plusNum minusNum < plusNum minusNum <= plusNum // Logical Operators !true true && true true || false https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html
  • 4. Q. 2 + 2 * 2 == 8 의 결과는? ① true ② false
  • 5. Not-Support Operators let hello = "Hello" let world = "World" let greeting = hello + world let noL = greeting - "l" let world5 = world * 5 greeting[-1] == "d" hello[1 ... 4] == "ello" Binary operator '-' cannot be applied to two 'String' operands Binary operator '*' cannot be applied to operands of type 'String' and 'Int' 'subscript(_:)' is unavailable: cannot subscript String with an Int, see the… 'subscript(_:)' is unavailable: cannot subscript String with an integer range, see …
  • 6. Customize Operators 1.Overload 2.Extension 3.Customize Operators hello[1 ... 4] == "ello" greeting[-1] == "d" let world5 = world * 5 let noL = greeting - "l"
  • 7. Operators Overload let hello = "Hello" let world = "World" let greeting = hello + world let noL = greeting - "l" // HeoWord let world5 = world * 5 // WorldWorldWorldWorldWorld let text = greeting - "," - " " + "!" * 2 // HelloWorld!! func - (_ origin: String, _ removal: String) -> String { return origin.replacingOccurrences(of: removal, with: "") } func * (_ origin: String, _ times: Int) -> String { return Array(1 ... times).map { _ in origin }.reduce("", +) }
  • 8. Extensions let hello = "Hello" let world = "World" let greeting = hello + world greeting[3] // "l" greeting[-1] // "d" extension String { subscript(i: Int) -> Character { var offset = i while offset < 0 { offset += count } let index = self.index(startIndex, offsetBy: offset) return self[index] } }
  • 9. Extensions let hello = "Hello" let world = "World" let greeting = hello + world hello[1 ... 4] // "ello" hello[1 ..< 4] // "ell" extension String { subscript(_ range: CountableClosedRange<Int>) -> Substring { let startIndex = index(self.startIndex, offsetBy: range.lowerBound) let endIndex = index(self.startIndex, offsetBy: range.upperBound) return self[startIndex ... endIndex] } subscript(_ r: CountableRange<Int>) -> Substring { let startIndex = index(self.startIndex, offsetBy: r.lowerBound) let endIndex = index(self.startIndex, offsetBy: r.upperBound) return self[startIndex ..< endIndex] } }
  • 11. Custom Operator let gray = UIView() gray.translatesAutoresizingMaskIntoConstraints = false gray.backgroundColor = .systemGray view.addSubview(gray) gray ~> view infix operator ~>: LogicalDisjunctionPrecedence @discardableResult func ~> (left: UIView, right: UIView) -> UIView { left.topAnchor.constraint(equalTo: right.topAnchor).isActive = true left.leftAnchor.constraint(equalTo: right.leftAnchor).isActive = true left.rightAnchor.constraint(equalTo: right.rightAnchor).isActive = true left.bottomAnchor.constraint(equalTo: right.bottomAnchor).isActive = true return left }
  • 12. Precedence Groups Group Name Associativity Example Priority BitwiseShiftPrecedence none << >> Higher Lower MultiplicationPrecedence left * / AdditionPrecedence left + - RangeFormationPrecedence none … ..< CastingPrecedence none as NilCoalescingPrecedence right ?? ComparisonPrecedence none < <= > >= == LogicalConjunctionPrecedence left && LogicalDisjunctionPrecedence left || TernaryPrecedence right ? : AssignmentPrecedence right += = *= -= /= https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations
  • 13. Custom Operator let green = UIView() green.translatesAutoresizingMaskIntoConstraints = false green.backgroundColor = .systemGreen view.addSubview(green) green.topAnchor ~> view.topAnchor + 50 green.centerXAnchor ~> view.centerXAnchor green.widthAnchor ~> 300 green.heightAnchor ~> 200 @discardableResult func ~> (left: NSLayoutXAxisAnchor, right: NSLayoutXAxisAnchor) -> NSLayoutXAxisAnchor { left.constraint(equalTo: right).isActive = true return left } @discardableResult func ~> (left: NSLayoutDimension, right: CGFloat) -> NSLayoutDimension { left.constraint(equalToConstant: right).isActive = true return left }
  • 14. Custom Operator let green = UIView() green.translatesAutoresizingMaskIntoConstraints = false green.backgroundColor = .systemGreen view.addSubview(green) green.topAnchor ~> view.topAnchor + 50 green.centerXAnchor ~> view.centerXAnchor green.widthAnchor ~> 300 green.heightAnchor ~> 200 @discardableResult func ~> (left: NSLayoutXAxisAnchor, right: (anchor: NSLayoutXAxisAnchor, constant: CGFloat)) -> NSLayoutXAxisAnchor { left.constraint(equalTo: right.anchor, constant: right.constant).isActive = true return left } func + (left: NSLayoutXAxisAnchor, right: CGFloat) -> (anchor: NSLayoutXAxisAnchor, constant: CGFloat) { (left, right) }
  • 15. Operating on functions func uppercased(_ text: String) -> String { return text.uppercased() } func output(_ it: Any) -> Void { print("(it)") } output(uppercased("Hello World")) // HELLO WORLD func ~> <A, B, C>(_ f1: @escaping (A) -> B, _ f2: @escaping (B) -> C) -> (A) -> C { { a in f2(f1(a)) } } (uppercased ~> output)("Hello World") // HELLO WORLD let upperPrinter = uppercased ~> output // (String) -> Void upperPrinter("Hello World") // HELLO WORLD
  • 16. Composition of functions func just<T>(_ f: @escaping () -> T) -> () -> T { { f() } } func map<T, U>(_ setter: @escaping (T) -> U) -> (T) -> U { { t in return setter(t) } } func output(_ it: Any) -> Void { print("(it)") } output( map({ $0.uppercased() })( just({ "Hello World" })() ) ) // HELLO WORLD
  • 17. Composition of functions func just<T>(_ f: @escaping () -> T) -> () -> T { { f() } } func map<T, U>(_ setter: @escaping (T) -> U) -> (T) -> U { { t in return setter(t) } } func output(_ it: Any) -> Void { print("(it)") } let fn = just { "Hello World" } ~> map { $0.count } ~> output fn(()) // 11 () -> String (String) -> Int (Any) -> () (()) -> ()
  • 18. Composition of functions @discardableResult func run<T>(_ f: (()) -> T) -> T { f(()) } run( just { "let us: Go! 2019" } ~> map { $0.uppercased() } ~> output ) // LET US: GO! 2019
  • 19. Q. 다음 중 custom operator 로 사용할 수 있는 것은? ① infix operator ~>: AdditionPrecedence ② infix operator ->: AdditionPrecedence ③ infix operator as: AdditionPrecedence ④ infix operator $$: AdditionPrecedence
  • 22. run( just { UIView() } ~> addSubView(view) ~> map { v -> UIView in v.backgroundColor = .systemGray v ~> self.view return v } ) let green = run( just { UIView() } ~> addSubView(view) ~> map { v -> UIView in v.backgroundColor = .systemGreen return v } ~> map { v -> UIView in v.topAnchor ~> self.view.topAnchor + 50 v.leftAnchor ~> self.view.leftAnchor + 50 v.rightAnchor ~> self.view.rightAnchor - 50 v.heightAnchor ~> 200 return v } )
  • 23. let yellow = run( just { UIView() } ~> addSubView(view) ~> map { v -> UIView in v.backgroundColor = .systemYellow return v } ~> map { v -> UIView in v.topAnchor ~> green.topAnchor + 100 v.centerXAnchor ~> self.view.centerXAnchor v.widthAnchor ~> 200 v.heightAnchor ~> 200 return v } ) run( just { UIView() } ~> addSubView(view) ~> map { v -> UIView in v.backgroundColor = .systemRed return v } ~> map { v -> UIView in v.centerXAnchor ~> yellow.centerXAnchor v.centerYAnchor ~> yellow.centerYAnchor v.widthAnchor ~> yellow.widthAnchor * 0.5 v.heightAnchor ~> yellow.heightAnchor / 2 return v } )
  • 24. let addSubView: (UIView) -> (UIView) -> UIView = { parent in { v in parent.addSubview(v) v.translatesAutoresizingMaskIntoConstraints = false return v } } @discardableResult func ~> (left: UIView, right: UIView) -> UIView { left.topAnchor.constraint(equalTo: right.topAnchor).isActive = true left.leftAnchor.constraint(equalTo: right.leftAnchor).isActive = true left.rightAnchor.constraint(equalTo: right.rightAnchor).isActive = true left.bottomAnchor.constraint(equalTo: right.bottomAnchor).isActive = true return left } @discardableResult func ~> (left: NSLayoutDimension, right: CGFloat) -> NSLayoutDimension { left.constraint(equalToConstant: right).isActive = true return left }
  • 25. @discardableResult func ~> (left: NSLayoutXAxisAnchor, right: NSLayoutXAxisAnchor) -> NSLayoutXAxisAnchor { left.constraint(equalTo: right).isActive = true return left } @discardableResult func ~> (left: NSLayoutXAxisAnchor, right: (anchor: NSLayoutXAxisAnchor, constant: CGFloat)) -> NSLayoutXAxisAnchor { left.constraint(equalTo: right.anchor, constant: right.constant).isActive = true return left } func + (left: NSLayoutXAxisAnchor, right: CGFloat) -> (anchor: NSLayoutXAxisAnchor, constant: CGFloat) { (left, right) } func - (left: NSLayoutXAxisAnchor, right: CGFloat) -> (anchor: NSLayoutXAxisAnchor, constant: CGFloat) { (left, -right) }
  • 26. @discardableResult func ~> (left: NSLayoutDimension, right: CGFloat) -> NSLayoutDimension { left.constraint(equalToConstant: right).isActive = true return left } @discardableResult func ~> (left: NSLayoutDimension, right: NSLayoutDimension) -> NSLayoutDimension { left.constraint(equalTo: right, multiplier: 1).isActive = true return left } @discardableResult func ~> (left: NSLayoutDimension, right: (anchor: NSLayoutDimension, multiplier: CGFloat)) -> NSLayoutDimension { left.constraint(equalTo: right.anchor, multiplier: right.multiplier).isActive = true return left } func * (left: NSLayoutDimension, right: CGFloat) -> (anchor: NSLayoutDimension, multiplier: CGFloat) { (left, right) } func / (left: NSLayoutDimension, right: CGFloat) -> (anchor: NSLayoutDimension, multiplier: CGFloat) { (left, 1 / right) }
  • 29. Summary 1. Operator Overloading, Extension, Custom Operator 을 활용해서 기능을 추가할 수 있다. 2. Operator는 Precedence 에 의한 연산 우선순위가 적용된다. 3. value 뿐 아니라 function 에도 연산자를 적용할 수 있다. 4. 복잡할 수 있는 연산을 간결하게 표현할 수 있다. 5. 코드의 가독성을 높일 수 있다. ( ⚠ 과하면 오히려 가독성을 해칠 수 있다 )
  • 30.