adnako adnako - 5 months ago 9
Swift Question

Swift: send type as argument and compare a variable's type with it

I want to implement a function like this one:

protocol Base {
var value: Int { get set }
}
class ObjectTypeA: Base {
var value: Int = 0
}
class ObjectTypeB: Base {
var value: Int = 1
}

var objects: [Base] = [ObjectTypeA(), ObjectTypeB()]
func updatePropertyForType(type: Base.Type, value: Int) {
objects.filter({ $0 is type }).forEach { // <<< ERROR IS HERE
var object = $0
object.value = value
}
}
updatePropertyForType(ObjectTypeB.self, value: 10)


But there is an error:

'type' is not a type


Please, help me fix it.

Answer

See this answer:

protocol Base: AnyObject {
    var value: Int { get set }
}
class ObjectTypeA: Base {
    var value: Int = 0
}
class ObjectTypeB: Base {
    var value: Int = 1
}

var objects: [Base] = [ObjectTypeA(), ObjectTypeB()]
func updatePropertyForType(type: Base.Type, value: Int) {
    objects.filter({let item = $0; return type === item.dynamicType }).forEach {
        $0.value = value
    }
}

call it with:

updatePropertyForType(ObjectTypeA.self, value: 3)