[swift-evolution] Eliminate inconsistencies among primary collection types

swiftevo.w.husmann at spamgourmet.com swiftevo.w.husmann at spamgourmet.com
Fri Apr 29 12:57:26 CDT 2016


A. When trying to declare nested collection types an inconsistency
   is unveiled:


A.1. “Array” as outer type allows for every collection type as inner
     type (“Int” used as a placeholder for “some other type”):

    let test_aa: Array<Array<Int>> = []
        // ok

    let test_as: Array<Set<Int>> = []
        // ok

    let test_ad: Array<Dictionary<Int, Int>> = []
        // ok


A.2. “Set” as outer type allows for “Set” as inner type only:

    let test_sa: Set<Array<Int>> = []
        // compile time error “Type 'Array<Int>' does not conform to 
        // protocol 'Hashable'”

    let test_ss: Set<Set<Int>> = []
        // ok

    let test_sd: Set<Dictionary<Int, Int>> = []
        // compile time error “Type 'Dictionary<Int, Int>' does not 
        // conform to protocol 'Hashable'”


A.3. The same is true for “Dictionary” as outer type:

    let test_da: Dictionary<Array<Int>, Int> = [:]
        // compile time error “Type 'Array<Int>' does not conform to 
        // protocol 'Hashable'”

    let test_ds: Dictionary<Set<Int>, Int> = [:]
        // ok

    let test_dd: Dictionary<Dictionary<Int, Int>, Int> = [:]
        // compile time error “Type 'Dictionary<Int, Int>' does not 
        // conform to protocol 'Hashable'”


B. When letting Swift infer the type of collections of “Array” from
   literals another inconsistency comes to light:


B.1. “Array” as outer type behaves IMHO perfectly:

    var testArray = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
    print(testArray.dynamicType)
        // prints “Array<Array<Int>>”
    testArray.append( [ 1, "five", 25, 625 ] );
        // compile time error “Cannot convert value of 'String' to
        // expected element type 'Int'”; type safe


B.2. “Set” as outer type works but there is no type safety:

    var testSet: Set = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
    print(testSet.dynamicType)
        // prints “Set<NSArray>”
    testSet.insert( [ 1, "five", 25, 625 ] )
        // neither run time nor compile time errors; no type safety


B.3. The same goes for “Dictionary” as outer type:

    var testDictionary = [
        [ 1, 2, 4, 8 ]: "Powers of Two",
        [ 1, 3, 9, 27 ]: "Powers of Three",
    ]
    print(testDictionary.dynamicType)
        // prints "Dictionary<NSArray, String>"
    testDictionary[ [ 1, "five", 25, 625 ] ] = "Powers of Five"
        // neither run time nor compile time errors; no type safety



— — - Wolfgang H.




More information about the swift-evolution mailing list