Does a mutating struct function in swift create a new copy of self?

前端 未结 3 2176
Happy的楠姐
Happy的楠姐 2020-12-20 17:08

I like value semantics in swift but I am worried about the performance of mutating functions. Suppose we have the following struct

struct Point          


        
3条回答
  •  甜味超标
    2020-12-20 17:49

    I did this:

    import Foundation
    
    struct Point {
      var x = 0.0
      mutating func add(_ t:Double){
        x += t
      }
    }
    
    var p = Point()
    
    withUnsafePointer(to: &p) {
      print("\(p) has address: \($0)")
    }
    
    p.add(1)
    
    withUnsafePointer(to: &p) {
      print("\(p) has address: \($0)")
    }
    

    and obtained in output:

    Point(x: 0.0) has address: 0x000000010fc2fb80

    Point(x: 1.0) has address: 0x000000010fc2fb80

    Considering the memory address has not changed, I bet the struct was mutated, not replaced.

    To replace completely something, you have to use another memory address, so it's pointless to copy back the object in the original memory address.

提交回复
热议问题