0

Given an array containing instances of several SubClasses (all having the same SuperClass), I want to check if all the elements of another array of required subClass Types are represented by the instances.

I came up with what I think is a valid solution, but I'm plagued by the error: Use of undeclared type 'requiredType' in the closure for requiredTypes.allSatisfy { ... }

class MyClass { }

class SubClass1: MyClass { }
class SubSubClass1: SubClass1 { }
class SubClass2: MyClass { }
class SubClass3: MyClass { }

let requiredTypes = [SubClass1.self, SubClass2.self]

let instances = [SubSubClass1(), SubClass2()]

let meetsRequirements = requiredTypes.allSatisfy { (requiredType) -> Bool in
    return instances.map({$0 is requiredType}).contains(true)
}
1
  • 3
    This is a code smell. I suspect what you're trying to do would be better achieved by formalizing it in a protocol. Commented Feb 7, 2019 at 18:42

1 Answer 1

4

is operator requires a type that is known at compile-time. You cannot use a variable there.

One possibility is to use type(of:), e.g.:

let meetsRequirements = requiredTypes.allSatisfy { requiredType in 
    instances.contains { type(of: $0) == requiredType }
}

Although that will be a problem with SubSubClass1.

If your classes inherit from NSObject, you can use:

let meetsRequirements = requiredTypes.allSatisfy { requiredType in 
    instances.contains { $0.isKind(of: requiredType) }
}

Checking whether a class inherits from a type which is stored in a variable is not currently supported in Swift. Usually it's a code smell.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.