Reading init() parameters inside a static function of a struct

Hello everyone,

Let’s say I’d like to calculate something and return the result of that calculation using a static function of a struct like so:

RandomStruct(10).calc()

If I’m not mistaken the value of “10” needs to be read from the struct’s init() method and a static function has to be used, so the code would have to look something like the following:

struct RandomStruct {
    static func calc() -> Int {
        return self.value + 2
    }

    var value = 0

    init(_ val: Int) {
        self.value = val
    }
}

This of course generates the “Instance member ‘…’ cannot be used on type ‘…’” error so my question is how exactly can this be done? Is it possible to use a value of an init() parameter in a static/class function? If so, how? Thank you in advance for any tips and suggestions.

Either use everything at a static level:

struct RandomStruct {
    static func calc(_ int: Int) -> Int {
        return int + 2
    }
}

or at an instance level:

struct RandomStruct {
    let int: Int

    func calc(_ int: Int) -> Int {
        return int + 2
    }
}

Mixing both seems unnecessary for your use here.

5 Likes

Completely agree with @Jon_Shier, but just wanted to mention one other option to achieve somewhat similar result:

func notAtAllAStruct(_ i: Int) -> (() -> Int) {
  return { () in i }
}

// which can be invoked as
let theIHolder = notAtAllAStruct(42)
_ = theIHolder() // this is your `.call()`

Yet again, without knowing the details, it sounds like a regular struct with instance methods will be a better option.

In your example “calc” is not a satic func. You’re calling calc on the instance returned by initilizing the struct with 10. I don’t see the need for static on your example.

2 Likes