Home > Back-end >  Bitwise inclusive or in Swift
Bitwise inclusive or in Swift

Time:10-02

I'm trying to rewrite Obj-C file to Swift. Everything is ok but i can't understand what's that (and how to rewrite it in Swift):

BOOL isSelected = NO;
isSelected |= self.date1 && [self.gregorian isDate:date inSameDayAsDate:self.date1];
isSelected |= self.date2 && [self.gregorian isDate:date inSameDayAsDate:self.date2];
rangeCell.selectionLayer.hidden = !isSelected;

I don't see such operator in Swift (i mean |=) and i can't figure out what that means. Date is subclass of NSDate in example

CodePudding user response:

Swift does have an |= operator. It's briefly mentioned in the Docs under the heading Operator Declarations

Operator Description
|= Bitwise OR and assign

However, it's not the right operator for the job, even in Objective-C. It happened to work, because BOOL bit-wise ORing of two bools happened to be identical to a logical ORing, but that was an coincidence of the implementation details.

In Swift, |= is specific to integer types which support bit-wise manipulations. The main implementation of it is defined for BinaryInteger. SwiftDoc has better docs on it, here. For Bool, you would use ||= (which doesn't have a SwiftDoc entry, unfortunately).

Personally, I wouldn't even use ||=. It works well when you have a long list of conditions, and you want to split their checks between multiple expressions. However, it defeats the short-circuiting behavior of ||, which I think is worse.

Here's how I would first write this:

let isSelected =
       self.date1.map { date1 in self.gregorian.isDate(date, inSameDayAs: date1) } ?? false
    || self.date2.map { date2 in self.gregorian.isDate(date, inSameDayAs: date2) } ?? false

rangeCell.selectionLayer.hidden = !isSelected

Looking over it, I see that what this is really doing, is checking if date is in the same day as date1 and date2, if they exist. It's really just a complicated way to do a range check. So let's do that:

let selectedDays = [self.date1, self.date2].compactMap { $0 }

let isSelected = selectedDays.contains(where: { selectedDay in
    self.gregorian.isDate(date, inSameDayAs: selectedDay)
})

rangeCell.selectionLayer.hidden = !isSelected
  • Related