Skip to content

Instantly share code, notes, and snippets.

protocol DogBreed {
typealias Level = Int
var breedName: String { get set }
var size: Level { get set }
var health: Level { get set }
var adaptability: Level { get set }
var intelligence: Level { get set }
var dogType: DogType { get set }
}
@kmkrn
kmkrn / mirrorsinswift2.swift
Last active December 17, 2017 15:50
Creating a simple mirror object
let husky = SiberianHusky()
let huskyMirror = Mirror(reflecting: husky)
//output: Mirror for SiberianHusky
for case let (label?, value) in huskyMirror.children {
print(label, value)
}
//prints:
//breedName Husky
//size 3
//health 4
//adaptability 3
//intelligence 3
extension Pomsky: CustomReflectable {
var customMirror: Mirror {
return Mirror(Pomsky.self, children: ["name": self.breedName , "size": self.size, "type" : self.dogType], displayStyle: .class, ancestorRepresentation: .generated)
}
}
let pomsky = Pomsky()
let pomskyMirror = Mirror(reflecting: pomsky)
for case let (label?, value) in pomskyMirror.children {
print(label, value)
let owner = DogOwner(name: "Pete", dog: husky)
let ownerMirror = Mirror(reflecting: owner)
print ("Pete owns a \(ownerMirror.descendant("dog", "breedName") ?? "some dog")")
//prints
//Pete owns a Husky
let children = ownerMirror.children
for child in children {
if child.label == "dog" {
let grandChildren = Mirror(reflecting: child.value).children
Mirror(reflecting: child.value).children
for grand in grandChildren {
if grand.label == "breedName" {
print("Pete owns a \(grand.value)")
}
}
class DogOwner {
var name: String
var dog: DogBreed
init(name: String, dog: DogBreed) {
self.name = name
self.dog = dog
}
}
protocol DogBreed {
typealias Level = Int
var breedName: String { get set }
var size: Level { get set }
var health: Level { get set }
var adaptability: Level { get set }
var intelligence: Level { get set }
var dogType: DogType { get set }
@kmkrn
kmkrn / catsv1.json
Created December 26, 2017 16:36
RealmCodable1
[
{
"catId" : 1,
"name": "Ashes",
"breed": "Bengal",
"weight" : 4.5
},
{
"catId" : 2,
"name": "Molly",
@kmkrn
kmkrn / Cat.swift
Last active December 29, 2017 23:37
import Foundation
import Realm
import RealmSwift
class Cat: Object, Decodable {
@objc dynamic var catId: Int = 0
@objc dynamic var name: String = ""
@objc dynamic var breed: String = ""
@objc dynamic var weight: Double = 0