Skip to content

Instantly share code, notes, and snippets.

@jessearmand
Created March 23, 2019 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessearmand/d7860f32a91f5fb159e4382c661fb416 to your computer and use it in GitHub Desktop.
Save jessearmand/d7860f32a91f5fb159e4382c661fb416 to your computer and use it in GitHub Desktop.
To test class mutation in Swift. The same behaviour as Kotlin, when the class has mutable properties
//: [Previous](@previous)
/*:
# Mutation
To test class mutation in Swift.
The same behaviour as Kotlin, when the class has mutable properties.
*/
import Foundation
import simd
class Node {
var position = float3(0)
var orientation = float4(0)
var name: String = ""
var children: [Node] = []
init(name: String) {
self.name = name
}
}
let transform: (Node) -> () = {
$0.children.forEach {
let timestamp = Date().timeIntervalSinceReferenceDate
$0.name = "\(timestamp)"
$0.position = float3(1.0, 1.0, Float.random(in: Range<Float>(uncheckedBounds: (lower: 1.0, upper: 10.0))))
$0.orientation = simd_quatf(angle: .pi / 4, axis: float3(0.0, 0.0, Float.random(in: Range<Float>(uncheckedBounds: (lower: 1.0, upper: 10.0))))).vector
}
}
let left = Node(name: "left")
let nodeA = Node(name: "A")
let nodeB = Node(name: "B")
left.children = [nodeA, nodeB]
let right = Node(name: "right")
right.children = [nodeA, nodeB]
let leftTree = [left, right]
let rightTree = leftTree.reversed()
let printNode: (Node) -> () = {
print("parent: \($0.name)")
$0.children.forEach {
print("child is \($0.name)")
print("position: \($0.position)")
print("orientation: \($0.orientation)")
}
}
print("left tree")
leftTree.forEach(printNode)
print("""
===========================
Start Mutation
===========================
""")
print("right tree")
rightTree.forEach(transform)
let nodeC = nodeA
nodeC.name = "C"
nodeC.position = float3(5.0, 5.0, 5.0)
print("node A \(nodeA.name), position: \(nodeA.position)")
rightTree.forEach(printNode)
print("""
===========================
Result
===========================
""")
print("left tree")
leftTree.forEach(printNode)
print("light tree")
rightTree.forEach(printNode)
//: [Next](@next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment