blockchain blockchain - 5 months ago 12
Swift Question

Swift - Initializing class variables which are classes

I am new to Swift. I am having trouble with declaring classes. I have the following -

class position_
{
var x: Float = 0
var y: Float = 0
}

class node_
{
var label: String = nil
var coordinates: position_
}


Now I can create an
initializer init()
in the
position_
class, like this -

class position_
{
var x: Float
var y: Float
init()
{
x = 0
y = 0
}
}


Is there anyway I can use this initializer in the
node_ class
? Because, without an
init()
function there is no way to initialize the coordinates variable in the
node_ class
. Or is there?

I find it hard to believe that Swift would require me to initialize each of the
position_
variables again in the
node_ class
. In other words is there a better option than the below one?

class node_
{
var label: String
var coordinates: position_
init()
{
name = nil
coordinates.x = 0
coordinates.y = 0
}
}


Also if I want to create another variable say "b" of type
UIButton
how do I initialize that? That is really what I want to do.

Answer

First every class name Start with capitalize character. So change your node_ class like this

class Node
{
    var label: String
    var coordinates: position_
    init()
    {
        name = ""
        coordinates = position_()
    }
}

Also change your class position_ with Position.
Instead of using _ try to write class name in capitalize first character of each word like this PositionMarker.
Hope this will help you.

Comments