SlideShare a Scribd company logo
송치원 (곰튀김)
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. 코드의 가독성을 높일 수 있다.
( ⚠ 과하면 오히려 가독성을 해칠 수 있다 )
끝

More Related Content

What's hot

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
Eleanor McHugh
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
Yahoo! JAPANとKotlin
Yahoo! JAPANとKotlinYahoo! JAPANとKotlin
Yahoo! JAPANとKotlin
Shoichi Matsuda
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::Exporter
Ricardo Signes
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
gsterndale
 
PHP 101
PHP 101 PHP 101
PHP 101
Muhammad Hijazi
 
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
osfameron
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & C
Eleanor 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 JVM
jwausle
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
Laiby Thomas
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
Richard 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 edition
osfameron
 
5th Sem SS lab progs
5th Sem SS lab progs5th Sem SS lab progs
5th Sem SS lab progs
Nagarjun Pakka Kannadiga
 
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からみたElixir
Kent 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 Go
Eleanor McHugh
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
brian d foy
 
Camping
CampingCamping

What's hot (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
 

Similar to 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 Scala
Hermann Hueck
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
Hermann 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
 
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 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 unchained
Eduard Tomàs
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
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
Eleanor McHugh
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
Stephan Janssen
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano 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 Scala
Siarhiej 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ées
Romain Lecomte
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Anıl Sözeri
 

Similar to 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
 

More from 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_만들면서 느껴보는 POP
Chiwon Song
 
20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?
Chiwon Song
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계
Chiwon Song
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversions
Chiwon Song
 
[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안
Chiwon Song
 
[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행
Chiwon Song
 
20190330 immutable data
20190330 immutable data20190330 immutable data
20190330 immutable data
Chiwon 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] 아두이노로 만드는 IoT
Chiwon 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
 

More from 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 프린터와 아두이노
 

Recently uploaded

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 

Recently uploaded (20)

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 

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.