Separating multiple if conditions with commas in Swift

后端 未结 6 1527
轮回少年
轮回少年 2020-11-30 13:56

We already know multiple optional bindings can be used in a single if/guard statement by separating them with commas, but not with && e.g.



        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 14:13

    Here is a case where they are sufficiently different as to require the ,. The following code will yield

    'self' captured by a closure before all members were initialized

    class User: NSObject, NSCoding {
    
        public var profiles: [Profile] = []    
        private var selectedProfileIndex : Int = 0
    
        public required init?(coder aDecoder: NSCoder) {
            // self.profiles initialized here
    
            let selectedIndex : Int = 100
            if 0 <= selectedIndex && selectedIndex < self.profiles.count {  <--- error here
                self.selectedProfileIndex = selectedIndex
            }
    
            super.init()
        }
    
    ...
    }
    

    This is due to the definition of && on Bool:

    static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool
    

    The selectedIndex < self.profiles.count on the RHS is caught in a closure.

    Changing the && to , will get rid of the error. Unfortunately, I'm not sure how , is defined, but I thought that this was interesting.

提交回复
热议问题