Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent duplicate code when initializing variables?

Tags:

swift

A class has some variables to be initialized in init() and at the same time, the class provides a function to restore these variables to their initial values in restoreInitValues(). Is there any way I can achieve this without setting these values twice (duplicate code) inside both init() and restoreInitValues()?

class Foo {
    var varA: Int
    var varB: Int
    var varC: Int

    init() {
        //restoreInitValues() // error: call method before all stored proproties are initalized

        //or I have to have duplicate code here as restoreInitValues below
        varA = 10
        varB = 20
        varC = 30
    }

    func restoreInitValues() {
        varA = 10
        varB = 20
        varC = 30
    } 
}
like image 503
Joe Huang Avatar asked Jul 25 '26 08:07

Joe Huang


2 Answers

Personally I would assign the 3 default values to 3 class scope constants, then use those values to init and restore. You could also eliminate the assigning statements in the init if you want, and assign the value when you declare the var. In addition, by having your defaults defined in a class constant if you need to add any other functions to the class they'll be available for use.

class Foo {
let defaultA = 10
let defaultB = 20
let defaultC = 20
var varA: Int
var varB: Int
var varC: Int

    init() {
    varA = defaultA
    varB = defaultB
    varC = defaultC
    }

    func restoreInitValues() {
    varA = defaultA
    varB = defaultB
    varC = defaultC
    } 
}

You could also define a struct, use it to assign your values, and then use your reset function to init.

struct values{

static let defaultA = 10
static let defaultB = 20
static let defaultC = 30

}


class test {

var a: Int = 0
var b: Int = 0
var c: Int = 0

    init(){
         resetValues()
    }

    func resetValues(){

        (a, b, c) = (values.defaultA, values.defaultB, values.defaultC)

    }

}
like image 155
Haligen Avatar answered Jul 28 '26 03:07

Haligen


Use implicitly unwrapped optionals.

class Foo {
    var varA: Int!
    var varB: Int!
    var varC: Int!

    init() {
        restoreInitValues()
    }

    func restoreInitValues() {
        varA = 10
        varB = 20
        varC = 30
    } 
}
like image 34
Code Avatar answered Jul 28 '26 03:07

Code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!