Foundation-Array

初级

  • 索引
    var students = ["Ben", "Ivy", "Jordell", "Maxime"]
     if let i = students.index(of: "Maxime") {
        students[i] = "Max"
    }
  -----------------------------------------------------
  -----------------------------------------------------
    let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    if let i = students.index(where: { $0.hasPrefix("A") }) {
         print("\(students[i]) starts with 'A'!")
    }
     // Prints "Abena starts with 'A'!"
  • 遍历
  let numberWords = ["one", "two", "three"]
   for word in numberWords {
         print(word)
    }
   // Prints "one"
    // Prints "two"
   // Prints "three"
   let numbers = [10, 20, 30, 40, 50, 60]
    numbers.forEach { word in
          print(word)
    }
  • 获取最小值方法
   let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
    let lowestHeight = heights.min()

    let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
    let leastHue = hues.min { a, b in a.value < b.value }
    print(leastHue)
    // Prints "Optional(("Coral", 16))"
  • 获取最大值
  let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
  let greatestHeight = heights.max()
  • 包含
 let cast = ["Vivien", "Marlon", "Kim", "Karl"]
 print(cast.contains("Marlon"))
 // Prints "true"

 let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
 let hasBigPurchase = expenses.contains { $0 > 100 }
 // 'hasBigPurchase' == true

中级

  • 移除n个元素
 let numbers = [1, 2, 3, 4, 5]
 print(numbers.dropLast(2))// 丢掉后面两个元素
  // Prints "[1, 2, 3]"
 print(numbers.dropLast(10))
  // Prints "[]"
  -----------------------------------------------------
  -----------------------------------------------------
 let numbers = [1, 2, 3, 4, 5]
 print(numbers.dropFirst(2))// 丢掉前面两个元素
 // Prints "[3, 4, 5]"
 print(numbers.dropFirst(10))
 // Prints "[]"
  • 截取元素
 let numbers = [1, 2, 3, 4, 5]
 print(numbers.suffix(2))// 从后面截取两个元素
 // Prints "[4, 5]"
 print(numbers.suffix(10))
 // Prints "[1, 2, 3, 4, 5]"
  -----------------------------------------------------
  -----------------------------------------------------
 let numbers = [10, 20, 30, 40, 50, 60]
  if let i = numbers.index(of: 40) {
       print(numbers.suffix(from: i))// 从i个元素开始截取到最后一个元素
   }
  // Prints "[40, 50, 60]"
  -----------------------------------------------------
  -----------------------------------------------------
  let numbers = [1, 2, 3, 4, 5]
  print(numbers.prefix(2))// 从前面截取2个元素
  // Prints "[1, 2]"
  print(numbers.prefix(10))
  // Prints "[1, 2, 3, 4, 5]"
  -----------------------------------------------------
  -----------------------------------------------------
   let numbers = [10, 20, 30, 40, 50, 60]
  if let i = numbers.index(of: 40) {
        print(numbers.prefix(upTo: i))// 从第一个元素开始截取第i-1个元素
    }
  // Prints "[10, 20, 30]"
  -----------------------------------------------------
  -----------------------------------------------------
  let numbers = [10, 20, 30, 40, 50, 60]
   if let i = numbers.index(of: 40) {
        print(numbers.prefix(through: i))// 从前面开始截取到第i个
     }
  // Prints "[10, 20, 30, 40]"
  • map的用法实例
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercaseString }
 // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.characters.count }
 // 'letterCounts' == [6, 6, 3, 4]
  • 过滤元素
 let cast = ["Vivien", "Marlon", "Kim", "Karl"]
 let shortNames = cast.filter { $0.characters.count < 5 }
 print(shortNames)
  // Prints "["Kim", "Karl"]"

高级

  • flatMap 和map的区别?
let array = [1,2,3,4]
let lessFourArray1 = array.flatMap { (x) -> Int? in
    return x < 4 ? x : nil
}
let lessFourArray2 = array.map { (x) -> Int? in
    return x < 4 ? x: nil
}
print(lessFourArray1)
print(lessFourArray2)

运行结果:

[1, 2, 3] [Optional(1), Optional(2), Optional(3), nil]

再看一个例子

  let numbers = [1, 2, 3, 4]
  let mapped = numbers.map { Array(count: $0, repeatedValue: $0) }
    // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
   let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $0) }
///     // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

提示:

实际上s.flatMap(transform)相当于Array(s.map(transform).joined())

总结:

flagMap 会解封可选值,并且会过滤掉空值nil

  • 分割字符串
  let line = "BLANCHE:   I don't want realism. I want magic!"
  print(line.characters.split(whereSeparator: { $0 == " " }) .map(String.init))
  // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
  -----------------------------------------------------
  -----------------------------------------------------
   //  指定最大的分割次数
   print(
        line.characters.split(
             maxSplits: 1, whereSeparator: { $0 == " " }
            ).map(String.init))
  // Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"
  -----------------------------------------------------
  -----------------------------------------------------
  print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }) .map(String.init))
  // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
  • 排序的用法

简单点

 let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
 let sortedStudents = students.sorted()// 默认从小到大
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
let descendingStudents = students.sorted(by: >)
 print(descendingStudents)
 // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

自定义排序规则

 enum HTTPResponse {
         case ok
         case error(Int)
     }

  let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
  let sortedResponses = responses.sorted {
        switch ($0, $1) {
        // Order errors by code
        case let (.error(aCode), .error(bCode)):
            return aCode < bCode
       // All successes are equivalent, so none is before any other
       case (.ok, .ok): return false
       // Order errors before successes
       case (.error, .ok): return true
       case (.ok, .error): return false
        }
    }
    print(sortedResponses)
   // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
  • zip 方法的用法

方法定义

zip<Sequence1 : Sequence, Sequence2 : Sequence>(_ sequence1: Sequence1, _ sequence2: Sequence2) -> Zip2Sequence<Sequence1, Sequence2>

用法

 let words = ["one", "two", "three", "four"]
 let numbers = 1...4
 let zipped = Array(zip(words, nnumbers))
// zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]

提示:

如果numbers和words元素的数量不一致,以最少者为准,不会出现报错!

  • 开头等于
 let a = 1...3
 let b = 1...10
print(b.starts(with: a))
// print true
  • 元素等于
let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
print(names.starts(with: ["Sofia"]))
// print true

提示:

集合对象不使用

  • reduce 方法的神奇用法

需求:请数组元素之和

 let numbers = [1, 2, 3, 4]
 let addTwo: (Int, Int) -> Int = { x, y in x + y }
 let numberSum = numbers.reduce(0, addTwo)
 //print 10
  • 几种比例方法的性能对比

a.for ... in

 var array:[Int] = []
for i in 0...1_000_000{
    array.append(i)
}
let date = NSDate()
for i in array{
}
print(NSDate().timeIntervalSince(date as Date))

运行结果:

0.00301897525787354

  • forEach
var array:[Int] = []
for i in 0...1_000_000{
    array.append(i)
}
let date = NSDate()
array.forEach { (a) in 
}
print(NSDate().timeIntervalSince(date as Date))

运行结果:

0.307871997356415

  • enumerated()
var array:[Int] = []
for i in 0...1_000_000{
      array.append(i)
}
let date = NSDate()
for (i,value) in array.enumerated(){ 
}
print(NSDate().timeIntervalSince(date as Date))

运行结果:

0.330793023109436

总结:

for... in的遍历速度是最快的,在数据量不大的情况下,使用三者中的任意一个都可以

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Swift3.0 - 流控制

    需求二: 输入一个顶点 判断是否在X轴上,或者Y轴上,或者既不在x轴,也不再Y轴上

    酷走天涯
  • Swift3.0 - 数据类型

    // 插入操作 shoppingList.insert("Maple Syrup", at: 0)

    酷走天涯
  • Foundation-String

    最近写完了Swift 3.0教程 ,在接下来这段时间,继续写Foundation 的教程,帮助大家更加深入,系统的学习Foundation 框架,可能会持续一段...

    酷走天涯
  • 变量的解构赋值

    上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。

    达达前端
  • php对象字段声明,easyswoole ORM 快速生成注释

    在PHPSTORM IDE中,我们可以通过注释给类写明可调用字段名,这样子才有语法提示。

    宣言言言
  • 通过欧拉计划学习Rust编程(第17~21题)

    最近想学习Libra数字货币的MOVE语言,发现它是用Rust编写的,所以先补一下Rust的基础知识。学习了一段时间,发现Rust的学习曲线非常陡峭,不过仍有快...

    申龙斌
  • DIY自己的AI助理,萝莉御姐暖男霸道总裁全凭你定义,微软小冰团队发布新框架

    别怕,很快,借助微软小冰团队刚刚推出的Avatar Framework(阿凡达框架),你就可以DIY一个自己的AI助理了。

    量子位
  • JavaScript学习笔记002-数据类型0字符串拼接

    [十位] [个位] [几何] [子集] [大圆] [小圆] [元素] [下标] [分子] [分母] [分数] [中点] [约分] [加数] [减数]

    Mr. 柳上原
  • 实战丨云开发帮你和「火箭少女」合个影!

    和平精英项目与“火箭少女”开启了主题活动。3月18日上线“火箭少女”101与游戏特种兵人脸融合的小程序活动。人脸融合技术由腾讯云AI团队提供支持,采用优图新融合...

    腾讯云开发TCB
  • TiKV 源码解析系列文章(十)Snapshot 的发送和接收

    TiKV 使用 Raft 算法来提供高可用且具有强一致性的存储服务。在 Raft 中,Snapshot 指的是整个 State Machine 数据的一份快照,...

    PingCAP

扫码关注云+社区

领取腾讯云代金券