Swift —— 6个快捷方法(数组求和、查找数组中最大或最小元素等)

1、将数组中每个元素的值乘以 2

let arr = (1...20).map{$0*2}
print(arr)

2、求一组数字的和

print((1...20).reduce(0, +))

3、找到数组中最小(或最大)的元素

let aaa = [10,-22,753,55,137,-1,-279,1034,77]
//Find the minimum of an array of Ints
print(aaa.sorted().first ?? 0)//-279
print(aaa.reduce(Int.max, min))//-279
print(aaa.min() ?? 0) //-279

//Find the maximum of an array of Ints
print(aaa.sorted().last ?? 0)//1034
print(aaa.reduce(Int.min, max))//1034
print(aaa.max() ?? 0)//1034

4、使用析构交换元组中的值

var a1 = 1, b1 = 2
(a1,b1) = (b1,a1)
print(a1, b1)

5、证明字符串中含有某个单词

let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"
//方法1:
print(!words.filter({tweet.contains($0)}).isEmpty) //true
//方法2:
print(words.contains(where: tweet.contains))// true
        
//方法3:
let result = tweet.characters
        .split(separator: " ")
        .lazy
        .map(String.init)
        .contains(where: Set(words).contains)
    print(result)// true

6、埃拉托色尼选筛法(就是求小于N的所有质数)

let n = 50
var primes = Set(2...n)
(2...Int(sqrt(Double(n)))).forEach {
   let _ = primes.subtract(stride(from: 2*$0, through: n, by: $0))
}
print(primes.sorted())

你可能感兴趣的:(Swift —— 6个快捷方法(数组求和、查找数组中最大或最小元素等))