简体   繁体   中英

How can I assign a Swift struct by reference?

As we know, in Swift, classes are reference objects whereas structs other data-types are value types. I'm trying to get the reference of a CGRect into a variable so I can change its value with a shorter name. Is there a way to achieve this? Attempting with an Objective-C or C++ pointer syntax is of no use here :(

let reference = someView.frame
frame = ...

If I stay at the view level it's ok because it's a reference type, but I want to include the frame in the reference.

You probably don't really want to work with references... I could be wrong, and you might have a good reason for wanting a reference. But looking at what you are trying to do, this might be a better approach:

  1. Assign the frame that you want to work with to a variable:

    var workingFrame = someView.frame

  2. Work with the copy, making any changes that you want to make:

    workingFrame = someNewRect

  3. Update someView.frame to the new value:

    someView.frame = workingFrame

There is, technically, a way to deal directly with pointers to memory addresses, but unless you have an amazingly good reason for going there, I think that most people would recommend that you avoid it.

[Edit:]

If you really want to try to work with pointers to memory addresses, then you may want to look at UnsafePointer<T> , UnsafeMutablePointer<T> , unsafeBitCast: and unsafeAddressOf: . Those types and functions will give you pointers to a struct.

For example, you can get a mutable pointer to an Int value like this:

let x = 5

let ptr: UnsafeMutablePointer<Int> = UnsafeMutablePointer(unsafeAddressOf(x))

Working with values, pointers, and memory addresses this way is discouraged, but yes, it is possible.

However, using unsafeAddressOf converts the Int to a class, so even that isn't really a pointer to the original struct. You may end up needing to initialize an UnsafeMutablePointer , allocate memory for it, and then assign a value to that memory. Then you can perform operations on the data at that memory address. Check out the documentation for UnsafeMutablePointer here.

And if you can give any more detail as to what, precisely, you are trying to do, there may be a more elegant solution. Swift does not make it easy to work with pointers, but it often provides other tools that allow you to accomplish what you need in a different way.

Here's the solution:

func pointerTo<T>(inout object: T) -> UnsafeMutablePointer<T> { 
    return withUnsafeMutablePointer(&object) {UnsafeMutablePointer<T>($0)}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM