How do I check if an object is a collection? (Swift)

前端 未结 3 1120
走了就别回头了
走了就别回头了 2021-01-05 11:51

I\'m extensively using KVC to build unified interface for the needs of an app. For instance, one of my functions gets an object, which undergoes several checks based solely

3条回答
  •  醉梦人生
    2021-01-05 12:48

    NOTE: This solution does NOT work with Swift 5+.

    func isCollection(object: T) -> Bool {
        switch object {
        case _ as Collection:
            return true
        default:
            return false
        }
    }
    

    Calling:

    // COLLECTION TESTING //
    
    let arrayOfInts = [1, 2, 3, 4, 5]
    isCollection(object: arrayOfInts) // true
    
    let setOfStrings:Set = ["a", "b", "c"]
    isCollection(object: setOfStrings) // true
    
    // [String : String]
    let dictionaryOfStrings = ["1": "one", "2": "two", "3": "three"]
    isCollection(object: dictionaryOfStrings) // true
    
    
    // NON-COLLECTION TESTING //
    
    let int = 101
    isCollection(object: int) // false
    
    let string = "string" // false
    
    let date = Date()
    isCollection(object: date) // false
    

提交回复
热议问题