Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Transcript of Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Swift done right
IVAN ĐIKIĆ
INTRO
• value types
• protocols
• functions as first class citizens
• generics
4 MAIN PILLARS OF SWIFT
SIDE NOTE: LET vs. VAR
let theAnswer = 42 // IMMUTABLE var theAnswer = 42 // MUTABLE
• var defines ordinary variable • let defines constant v
01 VALUE TYPES
SWIFT TYPES
• value types • instances keeps unique copy of its data • struct, enum or tuple • array, dictionary, set …
• reference types • instances share a single copy of the data • class
• Swift STL - 90% value types
EXAMPLE: value vs. reference
// Value type example struct S { var data: Int = -1 } var a = S() var b = a a.data = 42
print("\(a.data), \(b.data)") // prints "42, -1"
// Reference type example class C { var data: Int = -1 } var x = C() var y = x x.data = 42
print("\(x.data), \(y.data)") // prints "42, 42"
WHY VALUE TYPES
• reason about code
• performance
• threadsafe
HOW TO CHOOSE BETWEEN THE TWO
• value types (==) • you want copies to have independent state • data will be used in code across multiple threads
• examples • data model layer • API routers (e.g. Alamofire Router)
HOW TO CHOOSE BETWEEN TWO
• reference types (===, ==) • you want copies to have mutable, shared state • Cocoa
• examples • UIKit subclasses • API Managers • Singletons
02 HIGHER ORDER FUNCTIONS
“The highest level of abstraction possible, and no lower than the level at which you are
expert.”
IN SWIFT EVERYTHING IS A FUNCTION
• +, -, …
• you can pass them around
• you can apply them partially
• higher order functions • map, filter, reduce and friends
EXAMPLE: MAP
let moneyArray = [10, 20, 30, 40] var stringArray: [String] = []
// Naive approach for money in moneyArray { stringArray.append("\(money)$") }
// Swift approach stringArray = moneyArray.map { (money: Int) -> String in return "\(money)$" }
EXAMPLE: FILTER
let moneyArray = [10, 20, 30, 40] var filteredArray : [Int] = [] // Naive approach for money in moneyArray { if (money > 30) { filteredArray += [money] } }
// Swift approach filteredArray = moneyArray .filter { (money: Int) -> Bool in return money > 30 }
EXAMPLE: REDUCE
let moneyArray = [10, 20, 30, 40] var sum = 0 // Naive approach for money in moneyArray { sum = sum + money }
// Swift approach sum = moneyArray .reduce(0, combine: { (accumulator: Int, money: Int) -> Int in return accumulator + money })
IN SWIFT EVERYTHING IS A FUNCTION
• can be reduced to a simple for in loop
• nothing inherently different or special about how they work
• they can elevate your perspective about common
programming tasks
03 PROTOCOLS
SWIFT IS A PROTOCOL ORIENTED PROGRAMMING LANGUAGE
• single inheritance
• inheritance only for classes
• STL includes 54 public protocols • can do - “able” - `RawRepresentable` • is a - “type” - `CollectionType` • can be - “convertible” - `CustomStringConvertible`
• prefer composition instead of inheritance
EXAMPLE: inheritance
UIVIEWCONTROLLER
ROOT VIEW CONTROLLER
PROGRESSABLE VIEW CONTROLLER
LOGIN VIEW CONTROLLER
EXAMPLE: composition
LOGIN VIEW CONTROLLER PROGRESSABLE XY
EXAMPLE: protocol
protocol Progressable: NSObjectProtocol { func showLoading(message: String?)
. . . }
final class LoginViewController: UIViewController, Progressable { func showLoading(message: String?) { } . . . }
PROTOCOL EXTENSIONS
• extremely powerful feature
• useful for providing a default implementations
EXAMPLE: protocol extensionsprotocol Progressable: NSObjectProtocol { func showLoading(message: String?) . . . } extension Progressable where Self: UIViewController {
func showLoading(msg:String?) { SVProgressHUD.showWithStatus(
msg, maskType: SVProgressHUDMaskType.Gradient)
} . . . } final class LoginViewController: UIViewController, Progressable { ... }
04 GENERICS
GENERICS
• PROBLEM: • write code that is type agnostic
• SOLUTION • <T>
EXAMPLE: generic approach
protocol NumericType { func +(lhs: Self, rhs: Self) -> Self }
extension Float : NumericType {} extension Int : NumericType {}
func sum<T: NumericType>(x x:T, y:T) -> T { return x + y } sum(x: 1, y: 2) sum(x: 1.5, y: 2.1)
EXAMPLE: Array
public struct Array<Element> : ... { . . . }
var stringsArray = ["A","B","C"]
05 OPTIONALS
SWIFT’S WAY OF REPRESENTING NOTHINGNESS
• is a type that can represent • wrapped value • nothing
• is a concept that does exists in other languages (Haskell, Scala)
• is a type that supports usage of higher order functions on it
EXAMPLE: optional value
var perhapsInt: Int?
• WRONG: • “This is an Int, which is optional”
• RIGHT: • “This is an Optional, which may or may not hold and Int”
Q&A