根据布尔属性

时间:2016-05-20 08:48:55

标签: swift sorting swift2

我有一个对象数组。每个对象都有一个属性isUser: Bool。所以现在我想要排序那个数组,isUser == true的对象首先在数组中,然后是isUser == false的对象。

我是否需要同时对truefalse进行过滤,然后连接两个数组,或者这样做可以更简单吗?

4 个答案:

答案 0 :(得分:2)

我自己解决了。可以通过以下方式实现:

self.objectsOfFoo.sortInPlace { $0.isUser && !$1.isUser}

答案 1 :(得分:2)

您可以扩展Bool以使其具有可比性:处理true == 1false == 0。优点是您的代码更容易阅读:

extension Bool: Comparable {}

public func < (lhs: Bool, rhs: Bool) -> Bool {
    return Int(lhs) < Int(rhs)
}

self.objectsOfFoo.sortInPlace { $0.isUser > $1.isUser }

答案 2 :(得分:1)

您可以在Array之类的内容中对Swift 3.0进行排序。我尝试使用Bool

中的Swift 3.0媒体资源
yourArray.sort { (item1, item2) -> Bool in
                     var check1: Int = 0
                     var check2: Int = 0
                     if item1.isUser != nil, item1.isUser == true {
                        check1 = 1
                     }
                     if item2.isUser != nil, item2.isUser == true {
                        check2 = 1
                     }
                     return check1 > check2
                }

答案 3 :(得分:1)

sorted()将基于bool属性返回排序后的数组,而不会更改内容。

if (!context instanceof Activity) {
      //Your code
   }else{
      throw new RuntimeException("Text exception");
  }
相关问题