Add subscripts to access components of entity

This commit is contained in:
Christian Treffs 2020-07-16 14:01:12 +02:00
parent 13d0ea9f80
commit f72723c123
No known key found for this signature in database
GPG Key ID: 49A4B4B460BE3ED4
3 changed files with 47 additions and 0 deletions

View File

@ -31,4 +31,23 @@ extension Entity {
let compC: C? = get(component: C.self)
return (compA, compB, compC)
}
@inlinable
public subscript<C: Component, Value>(_ componentKeyPath: WritableKeyPath<C, Value>) -> Value? {
nonmutating set {
guard var comp = self.get(component: C.self),
let value = newValue else {
return
}
comp[keyPath: componentKeyPath] = value
}
get {
self.get(component: C.self)?[keyPath: componentKeyPath]
}
}
@inlinable
public subscript<C: Component>(_ componentType: C.Type) -> C? {
self.get(component: componentType)
}
}

View File

@ -81,6 +81,33 @@ class EntityTests: XCTestCase {
XCTAssertEqual(generator.count, 1)
}
func testEntitySubscripts() {
let nexus = Nexus()
let pos = Position(x: 12, y: 45)
let name = Name(name: "SomeName")
let entity = nexus.createEntity(with: pos, name)
XCTAssertEqual(entity[\Position.x], 12)
XCTAssertEqual(entity[\Position.y], 45)
XCTAssertEqual(entity[\Name.name], "SomeName")
entity[\Position.x] = 67
entity[\Position.y] = 89
entity[\Name.name] = "AnotherName"
XCTAssertEqual(entity[\Position.x], 67)
XCTAssertEqual(entity[\Position.y], 89)
XCTAssertEqual(entity[\Name.name], "AnotherName")
entity[\Velocity.a] = 123
XCTAssertNil(entity[\Velocity.a])
entity[Position.self]?.x = 1234
XCTAssertEqual(entity[Position.self]?.x, 1234)
XCTAssertNil(entity[Velocity.self]?.a)
}
}
extension Sequence {

View File

@ -29,6 +29,7 @@ extension EntityTests {
("testEntityEquality", testEntityEquality),
("testEntityIdentifierAndIndex", testEntityIdentifierAndIndex),
("testEntityIdGenerator", testEntityIdGenerator),
("testEntitySubscripts", testEntitySubscripts),
("testRemoveAllComponentsFromEntity", testRemoveAllComponentsFromEntity)
]
}