Swift 4 容器类型

2018-06-05  本文已影响31人  艺术农

数组

let evenNumber = [2, 3, 4, 5]

空数组,因为空数组元素为空,swift无法推断其内部元素的数据类型,所以需要显示指定其数组类型。

var emptyArray : [String] = []

创建带默认值的数组

let defaultArrat = Array(repeating: 0, count: 5)//[0,0,0,0,0]
var players = ["Alice", "Bob", "Cindy", "Dan"]
print(players.isEmpty)
// > false

first、last、min()、max()

print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)

range访问

let upcomingPlayersSlice = players[1...2]
print(upcomingPlayersSlice[1], upcomingPlayersSlice[2])
// > "Bob Cindy\n

upcomingPlayersSlice其实是指向源数组,所以元素根据下标访问的还是1和2。

let upcomingPlayersArray = Array(players[1...2])
print(upcomingPlayersArray[0], upcomingPlayersArray[1])
// > "Bob Cindy\n

上面我们通过Array方法返回了一个新数组,下标访问就成了0和1。

players[1...3].contains("Bob") // true
  1. 添加元素
players.append("Eli")
players += ["Gina"]
  1. 插入
players.insert("Frank", at: 5)
  1. 删除
var removedPlayer = players.removeLast()
print("\(removedPlayer) was removed")
// > Gina was removed

removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed

字典

字典的key和value可以是任意类型,但是所有的keys必须是同一类型,所有的value也必须是同一类型。

集合

和字典类似,只是value不会重复。

小练习

数组

let array1 = [Int]() // Valid
//let array2 = [] // Invalid: the type cannot be inferred
let array3: [String] = [] // Valid
let array4 = [1, 2, 3]
//: Which of the following five statements are valid
print(array4[0]) // Valid
//print(array4[5]) // Will compile, but will cause an error at runtime: index out of bounds
array4[1...2] // Valid
//array4[0] = 4 // Invalid: a constant array cannot be modified
//array4.append(4) // Invalid: a constant array cannot be modified
var array5 = [1, 2, 3]
//: Which of the five statements are valid?
array5[0] = array5[1]  // Valid
array5[0...1] = [4, 5] // Valid
//array5[0] = "Six" // Invalid: an element of type String cannot be added to an array of type [Int]
//array5 += 6 // Invalid: the += operator requires an array on the right-hand side, not a single element
for item in array5 { print(item) }  // Valid
func removingOnce(_ item: Int, from array: [Int]) -> [Int] {
  var result = array
  if let index = array.index(of: item) {
    result.remove(at: index)
  }
  return result
}
func removing(_ item: Int, from array: [Int]) -> [Int] {
  var newArray: [Int] = []
  for candidateItem in array {
    if candidateItem != item {
      newArray.append(candidateItem)
    }
  }
  return newArray
}
func reversed(_ array: [Int]) -> [Int] {
  var newArray: [Int] = []
  for item in array {
    newArray.insert(item, at: 0)
  }
  return newArray
}
func randomFromZero(to number: Int) -> Int {
  return Int(arc4random_uniform(UInt32(number)))
}
func randomized(_ array: [Int]) -> [Int] {
  var newArray = array
  for index in 0..<array.count {
    let randomIndex = randomFromZero(to: array.count)
    newArray.swapAt(index, randomIndex)
  }
  return newArray
}
func minMax(of numbers: [Int]) -> (min: Int, max: Int)? {
  if numbers.isEmpty {
    return nil
  }

  var min = numbers[0]
  var max = numbers[0]
  for number in numbers {
    if number < min {
      min = number
    }
    if number > max {
      max = number
    }
  }
  return (min, max)
}

字典

//let dict1: [Int, Int] = [:] // Invalid: type should be [Int: Int] not [Int, Int]
//let dict2 = [:] // Invalid: type cannot be inferred
let dict3: [Int: Int] = [:] // Valid
let dict4 = ["One": 1, "Two": 2, "Three": 3]
//: Which of the following are valid:
//dict4[1] // Invalid: key should be String, not Int
dict4["One"] // Valid
//dict4["Zero"] = 0 // Invalid: dict4 is a constant
//dict4[0] = "Zero" // Invalid: key should be a String and value should be an Int - and dict4 is a constant anyway
var dict5 = ["NY": "New York", "CA": "California"]
//: Which of the following are valid?
dict5["NY"]  // Valid
dict5["WA"] = "Washington" // Valid
dict5["CA"] = nil // Valid
func printLongStateNames(in dictionary: [String: String]) {
  for (_, value) in dictionary {
    if value.count > 8 {
      print(value)
    }
  }
}
func merging(_ dict1: [String: String], with dict2: [String: String]) -> [String: String] {
  var newDictionary = dict1
  for (key, value) in dict2 {
    newDictionary[key] = value
  }
  return newDictionary
}
func occurrencesOfCharacters(in text: String) -> [Character: Int] {
  var occurrences: [Character: Int] = [:]
  for character in text {
    if let count = occurrences[character] {
      occurrences[character] = count + 1
    } else {
      occurrences[character] = 1
    }
  }
  return occurrences
}
func occurrencesOfCharactersBonus(in text: String) -> [Character: Int] {
  var occurrences: [Character: Int] = [:]
  for character in text {
    occurrences[character, default: 0] += 1
  }
  return occurrences
}
func isInvertible(_ dictionary: [String: Int]) -> Bool {
  var seenValues: Set<Int> = []
  for value in dictionary.values {
    if seenValues.contains(value) {
      return false  // duplicate value detected
    }
    seenValues.insert(value)
  }
  return true
}
var nameTitleLookup: [String: String?] = ["Mary": "Engineer", "Patrick": "Intern", "Ray": "Hacker"]


nameTitleLookup.updateValue(nil, forKey: "Patrick")
nameTitleLookup["Ray"] = nil  // or nameTitleLookup.removeValue(forKey: "Ray")
上一篇下一篇

猜你喜欢

热点阅读