How to pass structure by reference?

2019-03-25 06:53发布

问题:

If I have some existing struct, but I want to use "Reference" behavior, how do I achieve that?

I can write some simple class-holder like

class Box<T> {
    var value: T
    init(_ value: T) {
        self.value = value
    }
}

I guess there must be ready class in the standard library, but I didn't find it.

I want to store that reference in my class, so inout parameter isn't what I need.

回答1:

For me the best variant was using class-holder:

class Ref<T> {
  var value: T

  init(_ value: T) {
    self.value = value
  }
}


回答2:

You can, but you should not store it in your class.

struct Size {
    var width:Float
    var height:Float
}

class Rect {
    var sizeRef:UnsafeMutablePointer<Size>
    init(_ size:UnsafeMutablePointer<Size>) {
        self.sizeRef = size
    }
    func doubleSize() {
        self.sizeRef.memory.height *= 2.0
        self.sizeRef.memory.width *= 2.0
    }
}  

var size = Size(width: 20.0, height: 20.0)
let rect = Rect(&size)
rect.doubleSize()
println("size: \(size.width) x \(size.height)") // -> size: 40.0 x 40.0

Because, usually, struct is allocated from "stack" memory, when you do like this:

func makeRect() -> Rect {
    var size = Size(width: 20.0, height: 20.0)
    return Rect(&size)
}

let rect = makeRect()

rect.sizeRef no longer points valid memory. UnsafeMutablePointer is unsafe in a literal sense.