Benn Tan Benn Tan - 11 days ago 7
Swift Question

Getting the initialiser values in Swift 3

Essentially I am creating a new data type called Vector3.

class Vector3 {

var x:Int
var y:Int
var z:Int


init(x:Int,y:Int,z:Int) {
self.x = x
self.y = y
self.z = z
}

}


I used the operator overloading feature in Swift in order to use operators on my custom data types.

infix operator +

func +(left:Vector3,right:Vector3) -> Vector3 {
return (Vector3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z))
}

var customVector = Vector3(x: 1, y: 2, z: 3)
var secondVector = Vector3(x: 3, y: 2, z: 1)

print(customVector + secondVector) //Take note


Currently the console is printing like this:

Vector3


Without the initialisation values, only with the class name.

However, WHAT I WANT is to print something like this:

Vector3(x:4,y:4,z:4)


Hopefully,someone can help me with this! Thanks!

NOTE:I am fully aware that one can get the values of these properties by:

customVector.x //1
customVector.y //2

Answer

Currently the console is printing like this: Vector3 without the initialisation values, only with the class name.

This is because you did not tell Swift how exactly you want your instances printed when you interpret them as strings. Make your class conformant to CustomStringConvertible protocol and implement description to print what you need:

class Vector3 : CustomStringConvertible {
    ...
    public var description: String {
        return "Vector3(x:\(x),y:\(y),z:\(z))"
    }
}