Unwrapping SCNVector3/SCNVector4 values to print?

血红的双手。 提交于 2019-12-23 04:12:31

问题


This should be an easy question

   import SceneKit
    import Accelerate

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

answer

vector C.SCNVector3

How to unwrap and display the vector like [ 1, 2, -8]?


回答1:


Update for Swift 2: In Swift 2, structures are by default printed with all properties:

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

You can customize the output by adopting the CustomStringConvertible protocol:

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]

Previous answer:

As Eric already explained, println() checks if the object conforms to the Printable protocol. You can add conformance for SCNVector3 with a custom extension:

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]



回答2:


If you go and look at the definition of SCNVector3 you will see that its a struct and doesn't have any methods to print nicely like you want. A struct in Swift that prints out a description would conform to the Printable protocol.

Since this struct doesn't do it for you, print out each component individually:

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

Output: Vector: [1.0, 2.0, -8.0]



来源:https://stackoverflow.com/questions/28885254/unwrapping-scnvector3-scnvector4-values-to-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!