Skip to content

Instantly share code, notes, and snippets.

View pofat's full-sized avatar

Pofat pofat

View GitHub Profile
@pofat
pofat / GetCreationTime.swift
Last active June 20, 2019 17:20
Get the timestamp of creation time of the process which runs your application in iOS
func getProcessStartTime() -> TimeInterval {
let pid = ProcessInfo.processInfo.processIdentifier
var procInfo = kinfo_proc()
var cmd: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
var size = MemoryLayout.stride(ofValue: procInfo)
if sysctl(&cmd, UInt32(cmd.count), &procInfo, &size, nil, 0) == 0 {
// tv_sec is timestamp measured in second; tv_usec is the rest fraction part in microsecond
return Double(procInfo.kp_proc.p_un.__p_starttime.tv_sec) * 1000.0 + Double(procInfo.kp_proc.p_un.__p_starttime.tv_usec) / 1000.0
} else {
print("Can't get information of process \(pid)")
@pofat
pofat / Requests.swift
Last active May 19, 2019 04:29
Implement basic network request with both protocol and generic struct
import Foundation
import RxSwift
enum HTTPMethod: String {
case POST, GET
}
// An object
@pofat
pofat / Sequence.swift
Created May 19, 2019 16:06
Definition of Sequence protocl
protocol Sequence {
associatedtype Element
associatedtype Iterator : IteratorProtocol where Iterator.Element == Element
func makeIterator() -> Iterator
}
protocol MyProcotol {}
struct MyStruct {
let x = 1
let y = 2
}
// What's the difference of following two?
let existentialContainer: MyProtocol = MyStruct()
let structInstance = MyStruct()
@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()
}
@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 / 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))")
struct ExistentialContainer {
var valueBuffer: (Int, Int, Int)
var vwt: UnsafePointer<ValueWitness>
var pwt: UnsafePointer<ProtocolWitness>
}
struct ProtocolWitness {
var descriptor: ProtocolConformanceDescriptor
var draw: FunctionRef
}
// From:
protocol Drawable {
func draw()
}
// To:
struct Drawing<Shape> {
var draw: (Shape) -> ()
}
import Foundation
import RxSwift
// MARK: Model
struct User: Decodable {
let id: Int
let name: String
}
let usersDecode: (Data) -> [User]? = { data in