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"))}

显示效果图
打印的生日歌

  • 过滤数组中的数字
 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)")

最大值和最小值打印结果

  • 埃拉托斯特尼筛法:用于查找所有的素数直到给定的上限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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值