I am studying swift.

I don't understand the code written on the following site.


In the [Japanese judgment] item

NSPredicate (format: "SELF MATCHES% @", range) .evaluate (with: self)

I read the official reference of NSPredicate, but I couldn't understand the contents.
In particular, I don't understand the meaning of the argument"SELF MATCHES% @" ;.

Thank you.

Official Reference NSPredicate

  • Answer # 1

    Cited sites

    [Swift] Validation String Extension collection using iOS default functions

    A little code excerpt from
    extension String {
        /// "Kanji" or not
        var isKanji: Bool {
            let range = "^ [\ u {3005} \ u {3007} \ u {303b} \ u {3400}-\ u {9fff} \ u {f900}-\ u {faff} \ u {20000}-\ u {2ffff}] + $"
            return NSPredicate (format: "SELF MATCHES% @", range) .evaluate (with: self)

    What does "SELF MATCHES% @"" mean?

    First SELF is from Literals,


      Represents the object being evaluated.

    In other words, the object to be evaluated, in this case self of evaluate (with: self).
    Since this code is a String extension, self is a String.

    MATCHES from String Comparisons


      The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

    Since it is

    , it checks whether SELF (target character string) on ​​the left side satisfies the regular expression on the right side.

    The right side is% @, but as in Parser Basics,


    The format string supports printf-style format specifiers such as% x (see Formatting String Objects). Two important format specifiers are% @ and% K.


    % @ is a var arg substitution for an object value—often a string, number, or date.

    Performs parameter expansion like the printf function.

    NSPredicate (format: "SELF MATCHES% @", range)

    So% @ is range,


    "^ [\ u {3005} \ u {3007} \ u {303b} \ u {3400}-\ u {9fff} \ u {f900}-\ u {faff} \ u {20000}- \ u {2ffff}] + $"


    This is a regular expression.

    In the end, we are checking whether the target string satisfies the above regular expression.

  • Answer # 2


    I don't understand the meaning of the argument "quote SELF MATCHES% @"".

    SELF(Since String is passed, String itself) is% @(arrangement range is assigned) andMATCHES(match ) Or not.

    From Japanese documentation


    MATCHES operator uses the ICU regular expression package, as shown in the following example:

    Because it is

    , it means whether the regular expression represented byrangematches self (String itself).