SWIFT中的单行代码

  • 数组中的每个元素乘以2
(1...20).map{$0*2}
  • 数组中的元素求和
(1...20).reduce(0,combine:+)
  • 验证在字符串中是否存在指定单词
let words = "hello"
let tweet = "hello , this is an example"

tweet.contains(words)
  • 读取文件
let path = NSBundle.mainBundle().pathForResource("test",ofType:"txt")
let lines = try? String(contentsOfFile:path!).characters.split{$0 == "\n"}.map(String.init)

if let lines == lines {
   lines[0]
   lines[1]
   lines[2]
   lines[3]
}
  • 打印生日歌
let name = "uraimo"
        (1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}

显示效果图
SWIFT中的单行代码_第1张图片

  • 过滤数组中的数字
 let part3 = [78,89,20,40,95,18].reduce(([],[]), combine: {(a:([Int],[Int]),n:Int) -> ([Int],[Int]) in (n<50) ? (a.0+[n],a.1) : (a.0,a.1+[n])
        })
  print(part3)  
  //打印结果
  ([20, 40, 18], [78, 89, 95])
  • 查询数组中的最小值和最大值
  //最小值
        let min0 = [-10,30,20,4].sort().first
        let min1 = [-10,30,20,4].reduce(Int.max, combine: min)
        let min2 = [-10,30,20,4].minElement()
        print("**\(min0)","++ \(min1)","##\(min2)")

  //最大值
        let max0 = [-10,30,20,4].sort().last
        let max1 = [-10,30,20,4].reduce(Int.min, combine: max)
        let max2 = [-10,30,20,4].maxElement()
        print("^^\(max0)","$$\(max1)","@@\(max2)")

SWIFT中的单行代码_第2张图片

  • 埃拉托斯特尼筛法:用于查找所有的素数直到给定的上限n
let n = 50
        var primes = Set(2...n)
        (2...Int(sqrt(Double(n)))).forEach{primes.subtractInPlace((2*$0).stride(through:n, by:$0))}
 print(primes.sort())

查找素数的打印结果

  • 元组数据交换
var a=1,b=2
(a,b)=(b,a)

a//2
b//1

你可能感兴趣的:(swift,SWIFT)