neoneye neoneye - 3 months ago 15
Swift Question

Swift countElements() with an array

Question



Is it possible to invoke
countElements()
with an
Array
in my setup?




Problem in detail



The
countElements()
works fine with
String
. However I cannot figure out how to cast
thing
to an
Array
and thus not invoking
countElements()
.

Please note that the method signature must be
func myCount(thing: Any?) -> Int
, since this is to be used in my open source project.

func myCount(thing: Any?) -> Int {
if thing == nil {
return -1
}
if let x = thing as? String {
return countElements(x)
}
if let y = thing as? Array<Any> {
return countElements(y) // this if is never taken
}
return -1
}

myCount(nil) // -1
myCount("hello") // 5
myCount([1, 2, 3]) // BOOM, returns -1, I'm expecting 3 returned

Answer

This is working for me. It feels a bit hacky though casting back and forth.

func myCount(thing: Any?) -> Int {
    if thing == nil {
        return -1
    }
    if let x = thing as? String {
        return countElements(x)
    }
    if let y = thing as? NSArray {
        return countElements(y as Array)
    }
    return -1
}