Skip to content

Instantly share code, notes, and snippets.

View zntfdr's full-sized avatar
🌙
BRB GOING TO THE MOON

Federico Zanetello zntfdr

🌙
BRB GOING TO THE MOON
View GitHub Profile
protocol JSONParser {
static func obtainModel(from json: JSON) -> Self?
}
// Some model
struct MyModel {
let name: String
let number: Int
let date: NSDate
}
// Conforming to the new protocol
extension MyModel: JSONParser {
static func obtainModel(from json: JSON) -> MyModel? {
let json = JSON(data: dataFromServer)
if let model = MyModel.obtainModel(from: json) {
// success
} else {
// failure
}
struct Node {
let name: String
var visited: Bool = false
var connections: [Connection] = []
init(name: String) {
self.name = name
}
}
struct Connection {
let to: Node
let weight: Int
init(to toNode: Node, weight: Int) {
assert(weight >= 0, "connection weight has to be equal or greater than zero")
self.to = toNode
self.weight = weight
}
struct Path {
let cumulativeWeight: Int
let lastNode: Node
let previousPath: Path?
}
init(toNode: Node, viaConnection: Connection?=nil, viaPath: Path?=nil) {
if let
previousPath = viaPath,
lastConnection = viaConnection {
self.cumulativeWeight = lastConnection.weight + previousPath.cumulativeWeight
} else {
self.cumulativeWeight = 0
}
self.lastNode = toNode
func ==(x: Path, y: Path) -> Bool {
return x.cumulativeWeight == y.cumulativeWeight
}
func <(x: Path, y: Path) -> Bool {
return x.cumulativeWeight < y.cumulativeWeight
}
struct Path: Comparable {
let cumulativeWeight: Int
let lastNode: Node
let previousPath: Path?
init(toNode: Node, viaConnection: Connection?=nil, viaPath: Path?=nil) {
if let
previousPath = viaPath,
lastConnection = viaConnection {
self.cumulativeWeight = lastConnection.weight + previousPath.cumulativeWeight
internal func shortestPath(source: Vertex, destination: Vertex) -> Path? {
var frontier: [Path] = [] {
didSet {
frontier.sortInPlace()
}
}
var finalPaths: [Path] = [] {
didSet {
finalPaths.sortInPlace()