swift Array中不存在filteredArrayUsingPredicate

时间:2014-06-24 09:08:05

标签: swift ios8 xcode6

我在数组中有“UserDetails”结构对象。我想从数组中过滤对象。但是在Swift数组中没有“filteredArrayUsingPredicate”的选项。

我的阵列创建

var arrayOfUsers:UserDetails[] = UserDetails[]()

我的userdetails代码是

struct UserDetails{
    var userName:String
    var userID:String
    var userAge:String
    func userDescription()->String{
        return "name " + userName + "age " + userID
    }
}

我创建对象的代码

        for a in 1...1000{
            var user:UserDetails = UserDetails(userName: "name", userID: String(a), userAge: "22")
            arrayOfUsers.append(user)
        }

现在我要过滤arrayOfUsers哪个用户ID为“1”。

5 个答案:

答案 0 :(得分:115)

Swift数组有一个.filter方法,它接受一个闭包 - 这样就可以了:

let filteredArray = arrayOfUsers.filter() { $0.userID == "1" }

可以通过多种方式简化闭包。关闭的完整声明看起来更像是这样:

var filteredArray = arrayOfUsers.filter( { (user: UserDetails) -> Bool in
        return user.userID == "1"
    })

两者之间的区别在于第一个是使用尾随闭包语法,速记参数名称,类型推断和隐式返回。您可以阅读more about closures in Apple's Swift documentation

答案 1 :(得分:93)

您也可以使用NSPredicate

    var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"];
    var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"];
    var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"];
    var attributeValue = "karthi";

    var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict];


    var namePredicate =
        NSPredicate(format: "firstName like %@",attributeValue);

    let filteredArray = arrNames.filter { namePredicate.evaluateWithObject($0) };
    println("names = ,\(filteredArray)");

// struct filtering

struct myStruct
{
    var userid:String;
    var details:String;
    init() {
        userid = "default value";
        details = "default";
    }

};
var f1 = myStruct();
f1.userid = "1";
f1.details = "Good boy";

var f2 = myStruct();
f2.userid = "2";
f2.details = "Bad boy";
var arrNames1:Array = [f1,f2];
let filteredArrayStruct =  arrNames1.filter( { (user: myStruct) -> Bool in
    return user.userid == "1"
    })
println("filter array count = \(filteredArrayStruct.count)");
for  filteredValues in filteredArrayStruct
{
       println("filteredArrayStruct = ,\(filteredValues.details)");
}

答案 2 :(得分:5)

如果您要过滤字典,可以这样做。

var visitors = [["age" : 22], ["age" : 41], ["age" : 23], ["age" : 30]]

var filteredVisitors = visitors.filter({
    $0["age"] < 30
})

println(filteredVisitors)
//[["age" : 22], ["age" : 23]]

同样适用于过滤其属性的结构

struct Person {
    var age : Int?
    init(age: Int) {
        self.age = age
    }
}

var eventAttendees = [Person(age: 22), Person(age: 41), Person(age: 23), Person(age: 30)]

var filteredAttendees = eventAttendees.filter({
    $0.age < 30
})

您可以参考这篇文章了解更多信息。 Filtering a Swift Array of Dictionaries or Object property

答案 3 :(得分:2)

在swift 3或4 中,您可以使用 NSPredicate 使用数组

let pred : NSPredicate = NSPredicate(format: "points_status = %@", "0")
let   approvalRequestArray =  approvalRequestOriginalArray.filtered(using: pred) as NSArray


let provincesStartingWithM = NSPredicate(format: "name contains [cd] 'a'")

provinces.filtered(using: provincesStartingWithM)

有关详细信息,请访问此链接 GitHub

答案 4 :(得分:1)

事实证明,您不必一次仅比较一个过滤器。您可以应用逻辑条件来扩展谓词的范围。例如:

 public static string GetTreeItemText(IntPtr treeViewHwnd, IntPtr hItem)
            {
                int ret;
                TVITEM tvi = new TVITEM();
                IntPtr pszText = LocalAlloc(0x40, MY_MAXLVITEMTEXT);

                tvi.mask = TVIF_TEXT;
                tvi.hItem = hItem;
                tvi.cchTextMax = MY_MAXLVITEMTEXT;
                tvi.pszText = pszText;

                ret = SendMessageTVI(treeViewHwnd, TVM_GETITEM, 0, ref tvi);
                string buffer = Marshal.PtrToStringUni((IntPtr)tvi.pszText,
                MY_MAXLVITEMTEXT);

                //char[] arr = buffer.ToCharArray(); //<== use this array to look at the bytes in debug mode

                LocalFree(pszText);
                return buffer;
            }

就像一个冠军。