Swift countElements () with array

Question

Can I call countElements()

with Array

in my setup?


Problem details

countElements()

works great with String

. However, I cannot figure out how to distinguish thing

from Array

and thus not invoke countElements()

.

Please note that the method signature must be func myCount(thing: Any?) -> Int

as it should 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

      

+3


source to share


1 answer


This works for me. It feels a little hacked but tossed 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
}

      

+2


source







All Articles