0

I need to initialize a variable depending on the OS version. I'm trying to use #available inside a `struct. I need to initialize a variable at the time of declaration.

Here is my code that I tried,

struct ColorConstants {

  static var os = 0
  #available(iOS 9, *)
  os = 9

  #available(iOS 10, *)
  os = 10
}

It gives me a build error:

Expected declaration

code error screenshot

Pramod More
  • 1,220
  • 2
  • 22
  • 51

1 Answers1

2

Not sure what you're actually trying to do, so there are probably better approaches, but based very literally on what you're showing in your question, you could try something like this:

static var os: Int {
    if #available(iOS 9, *) {
        return 9
    }
    if #available(iOS 10, *) {
        return 10
    }

    return 0
}
shim
  • 9,289
  • 12
  • 69
  • 108
  • I was trying to find the correct way of using #available inside a Struct for initializing a variable without any method as told in upper comments. – Pramod More Jun 08 '18 at 08:02
  • Your solution has worked for me, I will still try to edit my question for to be more clear – Pramod More Jun 08 '18 at 08:03
  • 1
    Yes you made it very clear that you're trying to use #available in a struct, but as I've said you have not explained what you're going to use this for. e.g. [there are other ways of getting the OS version](https://stackoverflow.com/a/24505884/1032372). The `#available` approach might not actually be what you want depending on your goal. – shim Jun 08 '18 at 08:04
  • Thanks for the link, but your solution will also work for so many other scenarios of coding when programmers will try use #available inside a Struct – Pramod More Jun 08 '18 at 08:08
  • Ok sure whatever have fun – shim Jun 08 '18 at 08:50