Swift and mutating struct

后端 未结 8 1751
鱼传尺愫
鱼传尺愫 2020-12-04 06:54

There is something that I don\'t entirely understand when it comes to mutating value types in Swift.

As the \"The Swift Programming Language\" iBook states:

8条回答
  •  余生分开走
    2020-12-04 07:22

    One more variant

    struct MyStruct {
        var myVar = "myVar"
        let myLet = "myLet"
    }
    
    func testMutateString() {
        //given
        let myStruct = MyStruct()
        
        //Change var
        //when
        var myStructCopy = myStruct
        myStructCopy.myVar = "myVar changed 1"
        
        //then
        XCTAssert(myStructCopy.myVar == "myVar changed 1")
        
        //Change let
        //when
        withUnsafeMutableBytes(of: &myStructCopy) { bytes in
            let offset = MemoryLayout.offset(of: \MyStruct.myLet)!
            let rawPointerToValue = bytes.baseAddress! + offset
            let pointerToValue = rawPointerToValue.assumingMemoryBound(to: String.self)
            pointerToValue.pointee = "myLet changed"
        }
        
        //then
        XCTAssert(myStructCopy.myLet == "myLet changed")
    }
    

    [Swift types]

提交回复
热议问题