Negate #available statement

后端 未结 5 617
南旧
南旧 2020-12-09 07:49

I want to execute a code block only on devices running with an OS older than iOS8. I can\'t do:

if #available(iOS 8.0, *) == false {
    doFoo()         


        
相关标签:
5条回答
  • 2020-12-09 08:34

    simple way to check is to create the function

    func isNewFeatureAvailable() -> Bool {
        if #available(iOS 9, *) {
            return true
        } else {
            return false
        }
    }
    

    Use:

    if isNewFeatureAvailable() {
        // use new api
    } else {
        // use old api
    }
    

    OR just use inline

        if #available(iOS 9, *) {
            // use new api
        } else {
            // use old api
        }
    
    0 讨论(0)
  • 2020-12-09 08:44

    Seems it's the best solution, before Swift2 you had to use other methods such as using ready-to-use classes wrote by individuals. But that's fine, you can set a variable in viewDidLoad() and use it to detect the older devices:

    var isNewerThan8: Bool = false
    
    func viewDidLoad(){
       if #available(iOS 8.0, *) { 
          isNewerThan8 = true
       } else { 
          isNewerThan8 = false
       }
    }
    
    func myFunction(){
       if isNewerThan8 {
         //foo
       }else{
        //boo
       }
    }
    
    0 讨论(0)
  • 2020-12-09 08:45

    I use a guard for this:

    guard #available(iOS 8.0, *) else {
        // Code for earlier OS
    }
    

    There's slight potential for awkwardness since guard is required to exit the scope, of course. But that's easy to sidestep by putting the whole thing into its own function or method:

    func makeABox()
    {
        let boxSize = .large
    
        self.fixupOnPreOS8()
    
        self.drawBox(sized: boxSize)
    }
    
    func fixupOnPreOS8()
    {
        guard #available(iOS 8, *) else {
            // Fix up
            return
        }
    }
    

    which is really easy to remove when you drop support for the earlier system.

    0 讨论(0)
  • 2020-12-09 08:45

    simple way to check is to create the function

    func isNewFeatureAvailable() -> Bool {
        if #available(iOS 9, *) {
            return true
        } else {
            return false
        }
    }
    

    Use:

    if isNewFeatureAvailable() {
        // use new api
    } else {
        // use old api
    }
    

    OR just use inline

    if #available(iOS 9, *) {
       // use new api
    } else {
       // use old api
    }
    
    0 讨论(0)
  • 2020-12-09 08:48

    It is not possible to have logic around the #available statement.

    Indeed, the statement is used by the compiler to infer what methods can be called within the scope it embraces, hence nothing can be done at runtime that would conditionally execute the block.

    It is possible though to combine conditions, using a comma, as follows

    if #available(iOS 8.0, *), myNumber == 2 {
      // some code
    }
    
    0 讨论(0)
提交回复
热议问题