Skip to content

Instantly share code, notes, and snippets.

Avatar
🌙
BRB GOING TO THE MOON

Federico Zanetello zntfdr

🌙
BRB GOING TO THE MOON
View GitHub Profile
View JSONParserProtocolUsageExample.swift
let json = JSON(data: dataFromServer)
if let model = MyModel.obtainModel(from: json) {
// success
} else {
// failure
}
View JSONParserProtocolConformingExample.swift
// 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? {
View JSONParserProtocol.swift
protocol JSONParser {
static func obtainModel(from json: JSON) -> Self?
}
View DijkstraNode.swift
struct Node {
let name: String
var visited: Bool = false
var connections: [Connection] = []
init(name: String) {
self.name = name
}
}
View DijkstraConnection.swift
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
}
View DijkstraPath-1.swift
struct Path {
let cumulativeWeight: Int
let lastNode: Node
let previousPath: Path?
}
View DijkstraPath-Init.swift
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
View DijstraPath-Comparable.swift
func ==(x: Path, y: Path) -> Bool {
return x.cumulativeWeight == y.cumulativeWeight
}
func <(x: Path, y: Path) -> Bool {
return x.cumulativeWeight < y.cumulativeWeight
}
View DijkstraPath.swift
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
View DijkstraShortestPath.swift
internal func shortestPath(source: Vertex, destination: Vertex) -> Path? {
var frontier: [Path] = [] {
didSet {
frontier.sortInPlace()
}
}
var finalPaths: [Path] = [] {
didSet {
finalPaths.sortInPlace()