简体   繁体   English

从 swift 三元运算符返回引用

[英]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.这可以在经典的 if/else 条件中完成,但不能在三元中完成。 Does anyone know why?有谁知道为什么?

I have a function which updates a struct.我有一个更新结构的函数。 This struct is passed as an inout myStruct parameter.此结构作为 inout myStruct 参数传递。 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.你不能像这样使用& ,因为 Swift 中的“地址”并不是真正的东西。 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:如果您不想进入不安全的指针,并且目标是根据条件调用带有 inout 参数&objectA&objectB的函数f ,请使调用本身有条件:

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

Just assign an object to myRef (and it must be a var !), then take reference on function call:只需将一个对象分配给myRef (并且它必须是一个var !),然后在函数调用时引用:

// 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)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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