0

I have a function below:

func check(_ type: Any.Type) {
        switch type {
           case is [String].Type
        ...
      }
}

For example:

class TaskContainer: Codable {
    let id: String
    let tasks: [String]
}
typealias TaskContainers = [TaskContainer]
check(TaskContainers.self)

How to check if an array is Codable?

Not working:

  • case is [Codable].Type
  • case is Array[Codable].Type
7
  • 1
    Why do you need to check that? You made the array; how can you not know whether its element is Codable? Commented Apr 26, 2018 at 20:13
  • 1
    You seem to be assuming that [TaskContainer].Type is a subtype of [Codable].Type, but it is not. What you are trying to do is highly unusual. If you tell us more about why you want to do this, maybe we can suggest a better way. Commented Apr 26, 2018 at 20:24
  • 1
    Almost anything you try here is likely to be unreliable, even if you get it working. Much of Swift is statically dispatched, so it will make choices at compile-time, not runtime. The fact that you are passing around Any.Type at all suggests a very deep type problem in your code. You should back up and think through the problem you're actually trying to solve, and we should be able to help you. Commented Apr 26, 2018 at 20:25
  • @robmayoff, it's a function in PerfectPostgreSQL. I need to add new type(Array of Codable objects) / Commented Apr 26, 2018 at 20:29
  • I took a quick look at Perfect-PostgreSQL and found no functions named check. Edit your question to show us how you're trying to use the library and what errors are occurring. Commented Apr 26, 2018 at 20:32

1 Answer 1

1

I'm not sure the reason for checking but this should work.

if let _ = TaskContainers.self as? Codable.Type {
    // Conforms to Codable protocol.
}
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.