Skip to content

Instantly share code, notes, and snippets.

View pofat's full-sized avatar

Pofat pofat

View GitHub Profile
@pofat
pofat / closure.swift
Created September 29, 2019 08:16
Discuss how closure capturing and capture list works
import Foundation
// struct for printing out instance address
struct MemoryAddress<T>: CustomStringConvertible {
let intValue: Int
var description: String {
let length = 2 + 2 * MemoryLayout<UnsafeRawPointer>.size
return String(format: "%0\(length)p", intValue)
}
@pofat
pofat / generic_and_protocol.swift
Created August 6, 2019 11:56
兩種宣告方式之間有什麼差異?
// 會帶真實型別進去
func doSomething<T: MyPotocol>(_ arg: T) { }
// 有 existentail container
func doSomething(_ arg: MyProtofcol) { }
@pofat
pofat / Describer.swift
Last active August 21, 2019 08:45
weak self podcast episode 1 附錄: 用 generic struct 取代 Protocol
/*
* Standard library 有個 protocol `CustomStringConvertible`,需要實作 `description: String` 來將一個物件轉化成 description string
* 但是若你對同一個物件想要有兩種描述方式,比如
* 想要用 JSON 的方式印出來 model 的所有 property,且希望有的時候是 pretty printed 有的時候是 sorted key 怎麼辦?
* 你會需要有兩個物件來遵守 CustomStringConvertible,因為一個 protocol 在一個物件裡只能有一種實作
* 然而用 generic struct 的話就能做到這件事
* 下面的實例中你可以宣告兩個不同的 instance ,`prettyPrintedDescribing` 和 `sortedKeyDescribing`
* 想用哪個就用哪個,方便多了,也讓 compiler 有更多參與最佳化的空間
*
*/
import Foundation
import RxSwift
// MARK: Model
struct User: Decodable {
let id: Int
let name: String
}
let usersDecode: (Data) -> [User]? = { data in
// From:
protocol Drawable {
func draw()
}
// To:
struct Drawing<Shape> {
var draw: (Shape) -> ()
}
struct ExistentialContainer {
var valueBuffer: (Int, Int, Int)
var vwt: UnsafePointer<ValueWitness>
var pwt: UnsafePointer<ProtocolWitness>
}
struct ProtocolWitness {
var descriptor: ProtocolConformanceDescriptor
var draw: FunctionRef
}
@pofat
pofat / Drawable.swift
Last active May 22, 2019 12:50
Protocol and conformance
protocol Drawable {
func draw()
}
struct Point: Drawable {
var x: Int
var y: Int
func draw() {
print("Draw a point at (\(x), \(y))")
@pofat
pofat / Requests.swift
Created May 20, 2019 15:52
Protocol Oriented Request
import Foundation
import RxSwift
// Requests
enum HTTPMethod: String {
case POST, GET
}
// Define what a request is
protocol Request {
@pofat
pofat / ExistentialContainer.swift
Last active May 20, 2019 15:35
Existential Conatiner
struct ExistentialContainer {
var valueBuffer: (Int, Int, Int)
var vwt: UnsafePointer<ValueWitness>
var pwt: UnsafePointer<ProtocolWitness>
}
protocol Fooable {
func foo()
}
protocol MyProcotol {}
struct MyStruct {
let x = 1
let y = 2
}
// What's the difference of following two?
let existentialContainer: MyProtocol = MyStruct()
let structInstance = MyStruct()