Negate #available statement

后端 未结 5 618
南旧
南旧 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: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.

提交回复
热议问题