Skip to content

Instantly share code, notes, and snippets.

@DianQK

DianQK/Rule.swift

Created Jul 31, 2017
Embed
What would you like to do?
PocketMole
struct Rule {
let index1: Int
let index2: Int
let index3: Int
let result: (_ value1: Int, _ value2: Int, _ value3: Int) -> Int
}
let rules: [Rule] = {
var rules: [Rule] = []
rules.append(Rule(index1: 0, index2: 1, index3: 6, result: { $0 + $1 + $2 }))
rules.append(Rule(index1: 1, index2: 8, index3: 2, result: { $0 + $1 ^ 2 + $2 * 2 }))
rules.append(Rule(index1: 2, index2: 0, index3: 6, result: { $0 * $1 + ($1 - $2) }))
rules.append(Rule(index1: 3, index2: 1, index3: 8, result: { $0 - $1 - $2 }))
rules.append(Rule(index1: 4, index2: 8, index3: 0, result: { $1 ^ $1 + $2 * 2 + $0^2 }))
rules.append(Rule(index1: 5, index2: 9, index3: 3, result: { $1 ^ $1 + $2 * 2 - $0^2 }))
rules.append(Rule(index1: 6, index2: 8, index3: 9, result: { $0 + $1 ^ $1 + $2 * 2 }))
rules.append(Rule(index1: 7, index2: 1, index3: 6, result: { $0 + $1 + $2 }))
rules.append(Rule(index1: 8, index2: 1, index3: 6, result: { $0 + $1 ^ $1 + $2 * 3 }))
rules.append(Rule(index1: 9, index2: 2, index3: 5, result: { $0 - $1 ^ 3 - $2 * 2 }))
return rules
}()
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let items = (1...rules.count).map { Variable($0) }
typealias SectionModel = RxDataSources.SectionModel<(), Observable<String>>
let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel>()
dataSource.configureCell = { dataSource, collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
item.bind(to: cell.label.rx.text).disposed(by: cell.reuseDisposeBag)
return cell
}
Observable.just(items)
.map { $0.map { $0.asObservable().map { "\($0)" } } }
.map { [SectionModel(model: (), items: $0)] }
.bind(to: collectionView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
collectionView.rx.itemSelected.asObservable().map { $0.row }
.map { index in rules.first(where: { $0.index1 == index })! }
.subscribe(onNext: { (rule) in
let value1 = items[rule.index1]
let value2 = items[rule.index2]
let value3 = items[rule.index3]
value1.value = rule.result(value1.value, value2.value, value3.value)
})
.disposed(by: disposeBag)
collectionView.rx.itemSelected.asObservable()
.subscribe(onNext: { [weak self] (indexPath) in
self?.collectionView.deselectItem(at: indexPath, animated: true)
})
.disposed(by: disposeBag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment