Swift's Brain-Opening Series (1)

 If we want to sort a list, in java we usually do:

// 我们将User按照排序号进行排序
List<User> userList = this.userService.loadAll();
Collections.sort(userList, new Comparator<User>() {
    @Override
    public int compare(User lh, User rh) {
        if (null == lh && null == rh)
            return 0;
        if (null == lh)
            return -1;
        if (null == rh)
            return 1;

        if (lh.getOrderNo() == rh.getOrderNo())
            return 0;
        return lh.getOrderNo() > rh.getOrderNo() ? 1 : -1;
    }
});

So how to do it in Swift?

The Swift standard library provides a sortmethod named , that sorts the values ​​in an array of known types according to the closure function you provide for sorting. Once sorted, the sort(_:)method returns a new array of the same size as the original array, containing elements of the same type, and the elements are properly sorted. The original array is not sort(_:)modified by the method.

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] 

func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

var reversed = names.sort(backwards)
// reversed为["Ewa", "Daniella", "Chris", "Barry", "Alex"]

Of course, the above method is quite verbose, but fortunately, Swift considers this situation and provides closures so that we can do it in the same way as anonymous classes in java .

Closure expression syntax is as follows:

{ (parameters) -> returnType in 
    statements
}

Closure expression syntax can take constants, variables, and inouttypes as parameters, but cannot provide default values. It is also possible to use variadic parameters at the end of the parameter list. Tuples can also be used as parameters and return values.

From this, our ordering above can be rewritten as follows:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] 
let reversed = names.sort({ (s1: String, s2: String) -> Bool in
    return s1 > s2
})

The function body part of the closure is inintroduced by the keyword. This keyword indicates that the parameters and return value types of the closure are defined, and the following will be the body of the closure function.

Since this sort function is very short, we can write them in one line, so the code will become:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = names.sort({ (s1: String, s2: String) -> Bool in return s1 > s2})

Perhaps you are already very satisfied with this sorting code. But don't forget that Swift 's type inference function is not a blow, because the sorting closure function is sort(_:)passed in as a method parameter. Can Swift infer the types of its parameters and return values ​​for us? That is, can we reduce the code to the following:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = names.sort({ s1, s2 in return s1 > s2})

I can tell you with great confidence that this is ok, even we removed the return prongs (->) and parentheses. Experience the power of Swift . But what I'm telling you is that we can continue to streamline here. In Swift , if the closure is a single-line expression, the result can returnbe implicitly returned by omitting the keyword, so that our code can be simplified to:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = names.sort({ s1, s2 in s1 > s2})

Well, I know what you're talking about, yes Swift provides parameter name abbreviations for inline closures, and we can use the parameters of the closure in order by $0, $1, . $2That is to say, our code can be further simplified to:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = names.sort({$0 > $1})

At this time, since all are function bodies, the inkeywords can be omitted together.

When you get here, do you admire Swift as if... (Some words are omitted here)

But, I'm going to tell you this isn't the ultimate downsizing, and you'd think I've gone crazy. Fortunately, I'm not crazy, it's Swift . In Swift , the Stringtype redefines (overloads) the implementation of the greater-than sign ( >), and of course the implementation of the less-than sign. The function accepts two Stringtypes of parameters and returns Boolthe value of the type. This is exactly sort(_:)the type of function required for the second parameter of the method, so our code is finally simplified as follows (if there is any other more concise, let me know, haha):

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = names.sort(>)

Ok, this time I'll be here first. I also just started to get in touch with Swift , and it feels very powerful and intelligent. It is easy to get started, but it is difficult to be familiar and proficient, but the development efficiency is higher than that of oc.

You can follow my WeChat public account (CD826Workshop) to communicate.

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326823454&siteId=291194637