Immutable/Mutable Collections in Swift

后端 未结 7 1431
不知归路
不知归路 2020-11-29 18:44

I was referring to Apple\'s Swift programming guide for understanding creation of Mutable/ immutable objects(Array, Dictionary, Sets, Data) in Swift language. But I could\'t

7条回答
  •  时光说笑
    2020-11-29 19:26

    [Unmodifiable and Immutable]

    Swift's array can be muted

    [let vs var, Value vs Reference Type]

    Immutable collection[About] - is a collection structure of which can not be changed. It means that you can not add, remove, modify after creation

    let + struct(like Array, Set, Dictionary) is more suitable to be immutable

    There are some classes(e.g. NSArray) which does not provide an interface to change the inner state

    but

    class A {
        var value = "a"
    }
    
    func testMutability() {
        //given
        let a = A()
        
        let immutableArr1 = NSArray(array: [a])
        let immutableArr2 = [a]
        
        //when
        a.value = "aa"
        
        //then
        XCTAssertEqual("aa", (immutableArr1[0] as! A).value)
        XCTAssertEqual("aa", immutableArr2[0].value)
    }   
    

    It would rather is unmodifiable array

提交回复
热议问题