Add access control for components

This commit is contained in:
Christian Treffs 2019-06-25 08:10:19 +02:00
parent 3f9bdf701f
commit 181d8cac51
4 changed files with 79 additions and 2 deletions

3
.gitignore vendored
View File

@ -29,6 +29,7 @@
.fseventsd
.LSOverride
.Spotlight-V100
.swiftpm/
.TemporaryItems
.Trashes
.VolumeIcon.icns
@ -51,4 +52,4 @@ playground.xcworkspace
Temporary Items
timeline.xctimeline
xcuserdata
xcuserdata/Package.resolveddocs/
xcuserdata/Package.resolveddocs/

View File

@ -1,4 +1,4 @@
// swift-tools-version:5.0.0
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription

View File

@ -0,0 +1,33 @@
//
// Component+Access.swift
//
//
// Created by Christian Treffs on 25.06.19.
//
@dynamicMemberLookup
public struct ReadableOnly<Comp> where Comp: Component {
@usableFromInline let component: Comp
public init(_ component: Comp) {
self.component = component
}
@inlinable public subscript<C>(dynamicMember keyPath: KeyPath<Comp, C>) -> C {
return component[keyPath: keyPath]
}
}
@dynamicMemberLookup
public struct Writable<Comp> where Comp: Component {
@usableFromInline let component: Comp
public init(_ component: Comp) {
self.component = component
}
@inlinable public subscript<C>(dynamicMember keyPath: ReferenceWritableKeyPath<Comp, C>) -> C {
nonmutating get { return component[keyPath: keyPath] }
nonmutating set { component[keyPath: keyPath] = newValue }
}
}

View File

@ -0,0 +1,43 @@
//
// AccessTests.swift
//
//
// Created by Christian Treffs on 25.06.19.
//
import FirebladeECS
import XCTest
class AccessTests: XCTestCase {
func testReadOnly() {
let pos = Position(x: 1, y: 2)
let readable = ReadableOnly<Position>(pos)
XCTAssertEqual(readable.x, 1)
XCTAssertEqual(readable.y, 2)
// readable.x = 3 // does not work and that's correct!
}
func testWrite() {
let pos = Position(x: 1, y: 2)
let writable = Writable<Position>(pos)
XCTAssertEqual(writable.x, 1)
XCTAssertEqual(writable.y, 2)
writable.x = 3
XCTAssertEqual(writable.x, 3)
XCTAssertEqual(pos.x, 3)
XCTAssertEqual(writable.y, 2)
XCTAssertEqual(pos.y, 2)
}
}