Inout无法与SubClass对象一起使用引发不能将不变值作为inout参数传递

时间:2018-06-28 12:03:49

标签: swift arkit inout

我有两个代码块

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
  // BLOCK 1 Which is not working 
    guard let planeAnchor = anchor as? ARPlaneAnchor else { return }

    var plane = Plane(with: planeAnchor) //IT IS SUBCLASS OF SCNNode
    var geo = plane.geometry
    plane.transform = SCNMatrix4MakeRotation(-.pi / 2, 1, 0, 0)

    update(&plane, withGeometry: plane.geo, type: .static)

   //Up here Cannot pass immutable value as inout argument: implicit conversion from 'Plane' to 'SCNNode' requires a temporary

    node.addChildNode(plane)

   // BLOCK 2 Which is working 


    let width = CGFloat(planeAnchor.extent.x)
    let height = CGFloat(planeAnchor.extent.z)
    let plane1 = SCNPlane(width: width, height: height)

    plane1.materials.first?.diffuse.contents = UIColor.white.withAlphaComponent(0.5)

    var planeNode = SCNNode(geometry: plane1)

    let x = CGFloat(planeAnchor.center.x)
    let y = CGFloat(planeAnchor.center.y)
    let z = CGFloat(planeAnchor.center.z)
    planeNode.position = SCNVector3(x,y,z)
    planeNode.eulerAngles.x = -.pi / 2

    update(&planeNode, withGeometry: plane1, type: .static)
    // WORKING FINE

    node.addChildNode(planeNode)

    self.planes[anchor.identifier] = plane

}

BLOCK1

当我尝试将其对象传递给需要class Plane: SCNNode的函数的对象时,我有了子类inout,它向我显示错误

  

无法将不变值作为inout参数传递:从“平面”到“ SCNNode”的隐式转换需要临时

如果我删除子类,那么它工作正常

这是为什么它是迅速的错误,或者我什么都没丢失?

2 个答案:

答案 0 :(得分:0)

由于使用“ init(_ anchor:ARPlaneAnchor)”初始化了Plane类,即使它被声明为SCNNode类,它也会返回与第2块中的纯SCNNode不同的实例。

我不是突变问题的专家,但我认为苹果博客The Role of Mutation in Safety

中有一个有趣的文档

不确定,但是由于类是易变的,因此您可以将更新功能作为(测试)解决方案移至Plane类

答案 1 :(得分:0)

Inout不适用于Subclass

这里是示例

class SuperClass {
    var name = "Prashant"

}

class TestObject:SuperClass {
}


func updateTemp ( object:inout SuperClass) {
    object.name = "P.T"
}

现在,当创建TestObject的子类SuperClass对象时,将不允许这样做。

var obj  = TestObject()
self.updateTemp(object: &obj) // Cannot pass immutable value as inout argument: implicit conversion from 'TestObject' to 'SuperClass' requires a temporary
print(obj.name)

如何解决此问题

三种方式

1)使用var obj:SuperClass = TestObject()

创建对象

2)实际上,因为类是引用类型,所以实际上不需要inout

3)像这样创建泛型函数(泛型很棒!)

func updateTemp<T:SuperClass> ( object:inout T) {
    object.name = "P.T"
} 

希望对某人有帮助

相关问题