【问题标题】:Unwrapping SCNVector3/SCNVector4 values to print?展开 SCNVector3/SCNVector4 值以打印?
【发布时间】:2015-03-05 18:37:51
【问题描述】:

这应该是一个简单的问题

   import SceneKit
    import Accelerate

    var str:SCNVector3 = SCNVector3Make(1, 2, -8)
    println("vector \(str)" 

回答

vector C.SCNVector3

如何解开并显示 [ 1, 2, -8] 这样的向量?

【问题讨论】:

    标签: ios swift scenekit


    【解决方案1】:

    Swift 2 更新: 在 Swift 2 中,默认情况下会打印结构 具有所有属性:

    let str = SCNVector3Make(1, 2, -8)
    print("vector \(str)")
    // Output:
    // vector SCNVector3(x: 1.0, y: 2.0, z: -8.0)
    

    您可以通过采用CustomStringConvertible 来自定义输出 协议:

    extension SCNVector3 : CustomStringConvertible {
        public var description: String {
            return "[\(x), \(y), \(z)]"
        }
    }
    
    let str = SCNVector3Make(1, 2, -8)
    print("vector \(str)")
    // Output:
    // vector [1.0, 2.0, -8.0]
    

    上一个答案:

    正如 Eric 已经解释过的,println() 检查对象是否符合 到Printable 协议。您可以为SCNVector3 添加一致性 带有自定义扩展:

    extension SCNVector3 : Printable {
        public var description: String {
            return "[\(self.x), \(self.y), \(self.z)]"
        }
    }
    
    var str = SCNVector3Make(1, 2, -8)
    println("vector \(str)")
    // Output:
    // vector [1.0, 2.0, -8.0]
    

    【讨论】:

    • Printable 已重命名为 CustomStringConvertible。谢谢sn-p!
    • @Crashalot:你完全正确,我已经更新了答案。谢谢你告诉我!
    • @MartinR 你在 SO 上教育的人比你意识到的要多。无需感谢任何人;我们都需要感谢你! :)
    【解决方案2】:

    如果您查看 SCNVector3 的定义,您会发现它是一个结构,并且没有任何方法可以像您想要的那样很好地打印。打印出描述的 Swift 结构将符合 Printable 协议。

    由于这个结构不适合你,所以单独打印出每个组件:

    println("Vector: [\(str.x), \(str.y), \(str.z)]")
    

    输出:向量:[1.0, 2.0, -8.0]

    【讨论】:

    • 谢谢,这会起作用,但我希望像 perl 一样对打印内联进行矢量化。
    猜你喜欢
    • 2013-02-22
    • 2019-10-14
    • 1970-01-01
    • 2014-07-29
    • 2016-04-16
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多