简体   繁体   English

快速转换协议类型以构造并作为inout传递

[英]Swift cast protocol type to struct and pass as inout

protocol ValueHolder {
}

struct A: ValueHolder {
    var value = 5
}

var x: ValueHolder = A()

func f(a: inout A) {
    a.value = 10
}

I want to use pass x to f. 我想将x传递给f。 Is it possible? 可能吗?

Edit: I understand all of the staff about value semantics and inout parameters. 编辑:我了解所有有关值语义和inout参数的人员。 The problem is that x needs to be casted to A and I wonder if that can be done without copying it ( as makes a typed copy of it) so that I can use f on x . 问题是x需要强制转换为A ,我想知道是否可以不复制而将其复制( as对它的类型化复制),以便可以在x上使用f

I want to use pass x (and not its copy) to f. 我想使用传递x(而不是它的副本)到f。 Is it possible? 可能吗?

Not exactly — at least, not if the parameter is an A. An A is a struct. 不完全是-至少,如果参数是A,则不是。A是结构。 Even with inout , a struct is still a value type. 即使使用inout ,结构仍然是值类型。 inout allows the original value to be replaced, but what it is replaced with is another A. Simply put, a struct cannot be mutated in place. inout允许替换原始值,但替换为另一个A。简单地说,无法在适当位置更改结构。

That being so, your question seems to lose its meaning. 既然如此,您的问题似乎失去了意义。 Since a struct cannot be mutated in place, there is no real reason to use inout here at all. 由于结构无法在适当位置进行突变,因此根本没有真正的理由在这里使用inout You are not doing anything that calls for inout . 您没有做任何需要 inout事情。 You might as well just drop the inout and accept the value semantics: 您不妨删除inout并接受值语义:

func f(a: A) -> A {
    var a = a
    a.value = 10
    return a
}
x = f(a:x as! A)

If you really want to keep the inout , then type a: as a ValueHolder and cast inside the function, like this: 如果您确实要保留inout ,则输入a:作为ValueHolder并在函数内部进行强制转换,如下所示:

var x: ValueHolder = A()
func f(a: inout ValueHolder) {
    var b = a as! A
    b.value = 10
    a = b
}
f(a:&x)
(x as! A).value // 10

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

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