altralaser
altralaser

Reputation: 2073

Initializing attributes in a different method

I have a class and initialize the attributes with default values:

class Point {
  var x : Int
  var y : Int

  public init() {
    x = 1
    y = 1
  }
}

Now I want to have a reset() method which sets the attributes to these default values. Because I want to prevent redundancies I try to move the lines from the initializer to the reset method and call this method from init:

class Point {
  var x : Int
  var y : Int

  public init() {
    reset()
  }

  public func reset() {
    x = 1
    y = 1
  }
}

But it doesn't work. It says that the attributes have to be initialized. How can I fix this issue?

Upvotes: 4

Views: 287

Answers (5)

dfrib
dfrib

Reputation: 73176

You could have two private type members that hold the default values for your x and y properties, and use these as default parameter values in your initializer (as well as use these when resetting a Point instance):

class Point {
    static private let xDefault = 1
    static private let yDefault = 1

    var x: Int
    var y: Int

    public init(x: Int = Point.xDefault, y: Int = Point.yDefault) {
        self.x = x
        self.y = y
    }

    public func reset() {
        x = Point.xDefault
        y = Point.yDefault
    }
}

let p1 = Point()
print(p1.x, p1.y)    // 1 1

let p2 = Point(y: 2)
print(p2.x, p2.y)    // 1 2
p2.reset()
print(p2.x, p2.y)    // 1 1

let p3 = Point(x: -1, y: 2)
print(p3.x, p3.y)    // -1 2
p3.reset()
print(p3.x, p3.y)    // 1 1

Upvotes: 1

Ashley Mills
Ashley Mills

Reputation: 53082

You can skip the init altogether…

class Point {
    var x = 1
    var y = 1

    public func reset() {
        x = 1
        y = 1
    }
}

Upvotes: 0

Anton  Malmygin
Anton Malmygin

Reputation: 3496

You can init your attributes on declaration

class Point {
  var x : Int = 1
  var y : Int = 1

  public init() {
  }

  public func reset() {
    x = 1
    y = 1
  }

While it add some duplication, it definitely solves your problem

Upvotes: 1

Alladinian
Alladinian

Reputation: 35616

Actually, you could provide default values at property declaration:

class Point {
    var x: Int = 1
    var y: Int = 1

    public init() {
        // No need to reset x & y
        // You can event omit init alltogether, if all properties have default values...
    }

    public func reset() {
        x = 1
        y = 1
    }
}

Upvotes: 1

Prerak Sola
Prerak Sola

Reputation: 10009

Declare your attributes optional like below.

class Point {
  var x : Int!
  var y : Int!

  public init() {
    reset()
  }

  public func reset() {
    x = 1
    y = 1
  }
}

Upvotes: -1

Related Questions