[swift-users] Checking/getting custom objects from a collection

Adriano Ferreira adriano.ferreira at me.com
Thu Apr 7 18:47:50 CDT 2016


Hi everyone!

I’m experimenting with Entity-Component Systems <https://en.wikipedia.org/wiki/Entity_component_system> and I’d appreciate if you could help me working on how to check/get custom objects from a collection.

The idea is to verify if an entity contains a particular component and, if so, retrieve it.

Here’s the API I’d like work on:


// Entity Library
class Character: Entity {}

// Component Library
class HealthComponent: Component {
    var health = 100.0
    var isDead = false
}

class AttackComponent: Component {
    var range = 0
    var damage = 0
}

// Usage
var healthComponent = HealthComponent()
var attackComponent = AttackComponent()

var components: [ComponentType] = [healthComponent, attackComponent]
var char = Character(components: components)

let hc = char.get(component: HealthComponent)
let ac = char.get(component: AttackComponent)


So, what are your thoughts on the TODOs below?

—

import Foundation

protocol ComponentType {
    var entity: EntityType? { get }
}

protocol EntityType {
    var components: [ComponentType] { get }
    func get<T: ComponentType>(component c: T.Type) -> T?
    func add(component c: ComponentType)
    func remove(component c: ComponentType)
}

class Component: ComponentType {
    var entity: EntityType?
}

class Entity: EntityType {
    var components = [ComponentType]()

    init(components: [ComponentType]) {
        for component in components {
            self.add(component: component)
        }
    }

    func get<T: ComponentType>(component c: T.Type) -> T? {
        // TODO: - not sure how to work the types here
        // if `self` contains component of given type, return it
        // otherwise, return nil
    }

    func add(component c: ComponentType) {
        // TODO: - depends on the `get` function
        // if `self` already contains component, just return
        // otherwise, self.components += [component]
    }

    func remove(component c: ComponentType) {
        // TODO: - also depends on the `get` function
        // if `self` contains component, remove it
        // otherwise, just return
    }
}



Best,

—A
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160407/8ca4d1be/attachment.html>


More information about the swift-users mailing list