Using Predicate in Swift

后端 未结 8 910
陌清茗
陌清茗 2020-12-07 12:16

I\'m working through the tutorial here (learning Swift) for my first app: http://www.appcoda.com/search-bar-tutorial-ios7/

I\'m stuck on this part (Objective-C code)

8条回答
  •  死守一世寂寞
    2020-12-07 12:45

    This is really just a syntax switch. OK, so we have this method call:

    [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
    

    In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …] would become NSPredicate(format: …). (For another example, [NSArray arrayWithObject: …] would become NSArray(object: …). This is a regular pattern in Swift.)

    So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @"", but in Swift we just use quotation marks for strings. So that gives us:

    let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
    

    And in fact that is exactly what we need here.

    (Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] \(searchText)". That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)

提交回复
热议问题