0

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.

2 Answers 2

1
  1. You don't have to initialize every variable again because each time you create new instance of a class, structure or enumeration, their stored properties have initial value.

  2. Always try to provide a default value rather then setting a value within an initializer. If a class or structure provides default values for all its properties Swift automatically gives you a default initializer.

    class Position {  
        var x: Float = 0   
        var y: Float = 20  
    }
    
    let position = Position() // nice!
    
  3. Position class is a very simple data construct - it feels like the Struct type would fit better here.

  4. Final code - with UIButton

    struct Position {  
        var x: Float = 0  
        var y: Float = 20  
    }
    
    class Node {  
        var label = "" // label is inferred to be of type String  
        var coordinates = Position()  
        var button = UIButton(type: .InfoDark)  
    }
    
    let myNode = Node()
    
Sign up to request clarification or add additional context in comments.

Comments

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.