简体   繁体   中英

Why sort([1,2,3]){true} doesn't work in Swift?

我知道这个例子是完全没有用的和人为的,但是我试图更好地围绕Swift中的值处理方式,我不明白为什么下面的代码会返回错误。

var notSorted = sort([1,2,3,4]){true}

The second parameter of sort has type (T, T) -> Bool , but you are supplying a () -> Bool , namely a closure with no parameters that returns true .

Of course the two types don't match and you rightfully get a compile-time error.

Something like this will work:

var notSorted = sort([1,2,3,4]){_ in true}

By the way, that closure has the effect of reversing the array. If you want to perform a nop, you have to put false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM