swiftswift-structs

Swift - using #available inside Struct for initializing variable


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


Solution

  • 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
    }