简体   繁体   中英

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.

  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() 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM