简体   繁体   中英

Return references from a swift ternary operator

let myRef = isTrue() ? &objectA : &objectB

errors: "Use of extraneous '&'"

This can be done within a classic if/else conditional, but not in a ternary. Does anyone know why?

I have a function which updates a struct. This struct is passed as an inout myStruct parameter. The ternary operator is to determine which struct to pass to the function

Ah. It would have been helpful to say that in the original question.

You can't use & like that because an "address" in Swift isn't really a thing. If you don't want to get into unsafe pointers, and if the goal is to call a function f with inout argument &objectA or &objectB depending on a condition, make the call itself conditional:

isTrue() ? f(&objectA) : f(&objectB)

Just assign an object to myRef (and it must be a var !), then take reference on function call:

// Given
struct Test {
    var x: String
}

func isTrue() -> Bool {
    return Bool.random()
}

func byRef(test: inout Test) {

    test.x = String(test.x.reversed())
}

let objectA = Test(x: "hello")
let objectB = Test(x: "hola")

// Now create a ref
// Note that it MUST be a var (not let)
var myRef = isTrue() ? objectA : objectB

// Now we can pass it to a function
print("Before: \(myRef.x)")
byRef(test: &myRef)
print("After: \(myRef.x)")

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