iOS 攻城蝨 at pipimy inc.
struct Student {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let students = [
Student(name: "Calvin", age: 25), Student(name: "Fenny", age: 23),
Student(name: "Bob", age: 32), Student(name: "Tian", age: 35)
]
var ageBelow30 = [Student]()
for student in students {
if student.age < 30 {
ageBelow30.append(student)
}
}
var names = [String]()
for student in students {
names.append(student.name)
}
var ageBelow30Names = [String]()
for student in students {
ageBelow30Names.append(student.name)
}
let ageBelow30 = students.filter { $0.age < 30 }
let names = students.map { $0.name }
let ageBelow30Names = students.filter { $0.age < 30 } .map { $0.name }
let ageBelow30Names = students.reduce([]) { (result, student) -> [String] in
if student.age < 30 {
var nextResult = result
nextResult.append(student.name)
return nextResult
}
return result
}
以 Data Flow 為中心,有事件發生就及時反應的編程思維
ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.
整個 RX 都是 Obserbable
query.rx.text
.filter {string in
return string.characters.count > 3
}
.debounce(0.51, scheduler: MainScheduler.instance)
.map {string in
let apiURL = URL(string: "https://api.github.com/q?=" + string)!
return URLRequest(URL: apiURL)
}
.flatMapLatest { request in
return URLSession.shared.rx.data(request)
}
.map { data —> [AnyObject] in
let json = try JSONSerialization.JSONObject(with: data, options: [])
return json as! [AnyObject]
}
.map {object in
return Repo(object: object)
}
.bindTo(tableView.rx.items(cellIdentifier("Cell"))
其實不太一樣,待稍後提提 (有機會再說)
Text
超短改寫 Present
In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.
This page explains what the reactive pattern is and what Observables and observers are (and how observers subscribe to Observables). Other pages show how you use the variety of Observable operators to link Observables together and change their behaviors.
死命趕也來不及在今天 Present 的 Project
iOS - RxSwift, Server - Express
其實後面有改 cocoaheads