Swift 语言基础(3)-数组和字典类型

这篇博客深入探讨了Swift中的数组和字典类型。从Array Literals开始,介绍了如何创建和遍历数组,接着转向字典,讲解了字典字面量、访问与修改字典元素的方法以及如何遍历字典。此外,还涵盖了如何创建空字典对象和理解Swift中的可变性概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Arrays

Array Literals

var shoppingList: String[] = ["Eggs","Milk"]
 // shoppingList has been initialized with two initial items

varshoppingList = ["Eggs","Milk"]

println("The shopping list contains\(shoppingList.count)items.")
 // prints "The shopping list contains 2 items."

 ifshoppingList.isEmpty{
 println("The shopping list is empty.")
 }else {
 println("The shopping list is not empty.")
 }
 // prints "The shopping list is not empty."


  shoppingList . append ( "Flour" )
  // shoppingList now contains 3 items, and someone is making pancakes

 shoppingList+= "Baking Powder"
 // shoppingList now contains 4 items

 shoppingList+= ["Chocolate Spread","Cheese","Butter"]
 // shoppingList now contains 7 items

 varfirstItem = shoppingList[0]
 // firstItem is equal to "Eggs"

shoppingList[0] = "Six eggs"
 // the first item in the list is now equal to "Six eggs" rather than "Eggs"

 shoppingList[4...6] = ["Bananas","Apples"]
 // shoppingList now contains 6 items

 shoppingList.insert("Maple Syrup", atIndex: 0)
 // shoppingList now contains 7 items
 // "Maple Syrup" is now the first item in the list


 letmapleSyrup = shoppingList.removeAtIndex(0)
 // the item that was at index 0 has just been removed
 // shoppingList now contains 6 items, and no Maple Syrup
 // the mapleSyrup constant is now equal to the removed "Maple Syrup" string


firstItem= shoppingList[0]
 // firstItem is now equal to "Six eggs"

letapples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no cheese
// the apples constant is now equal to the removed "Apples" string


数组遍历

 foritem in shoppingList {
println(item)
 }
 // Six eggs
 // Milk
 // Flour
 // Baking Powder
 // Bananas


 for(index,value)in enumerate(shoppingList) {
println("Item\(index+ 1):\(value)")
 }
 // Item 1: Six eggs
 // Item 2: Milk
 // Item 3: Flour
 // Item 4: Baking Powder
 // Item 5: Bananas


 varsomeInts = Int[]()
 println("someInts is of type Int[] with\(someInts.count)items.")
 // prints "someInts is of type Int[] with 0 items."

 someInts.append(3)
 // someInts now contains 1 value of type Int
 someInts= []
 // someInts is now an empty array, but is still of type Int[]


varthreeDoubles = Double[](count:3,repeatedValue:0.0)
// threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0]

 varanotherThreeDoubles = Array(count:3,repeatedValue:2.5)
 // anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]

  var sixDoubles = threeDoubles + anotherThreeDoubles
  // sixDoubles is inferred as Double[], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

字典

字典字面量

[ key 1 : value 1 , key 2 : value 2 , key 3 : value 3 ]

 varairports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"]

var airports = [ "TYO" : "Tokyo" , "DUB" : "Dublin" ]

访问与修改字典对象


 println("The dictionary of airports contains \(airports.count)items.")
 // prints "The dictionary of airports contains 2 items."

 airports["LHR"] = "London"
 // the airports dictionary now contains 3 items

 airports["LHR"] = "London Heathrow"
 // the value for "LHR" has been changed to "London Heathrow"

 if letoldValue = airports.updateValue("Dublin International", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
 }
 // prints "The old value for DUB was Dublin."


 if letairportName = airports["DUB"] {
println("The name of the airport is \(airportName).")
 }else {
println("That airport is not in the airports dictionary.")
 }
 // prints "The name of the airport is Dublin International."


 airports["APL"] = "Apple International"
 // "Apple International" is not the real airport for APL, so delete it
 airports["APL"] = nil
 // APL has now been removed from the dictionary


 if letremovedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
 }else {
println("The airports dictionary does not contain a value for DUB.")
 }
 // prints "The removed airport's name is Dublin International."


字典遍历

 for(airportCode,airportName)in airports {
println("\(airportCode):\(airportName)")
 }
 // TYO: Tokyo
 // LHR: London Heathrow


 forairportCode in airports.keys{
 println("Airport code: \(airportCode)")
 }
// Airport code: TYO
 // Airport code: LHR


forairportName in airports.values{
println("Airport name: \(airportName)")
 }
// Airport name: Tokyo
// Airport name: London Heathrow



 letairportCodes = Array(airports.keys)
 // airportCodes is ["TYO", "LHR"]
letairportNames = Array(airports.values)
 // airportNames is ["Tokyo", "London Heathrow"]


创建空字典对象

 varnamesOfIntegers = Dictionary<Int,String>()
 // namesOfIntegers is an empty Dictionary<Int, String>

 namesOfIntegers[16] = "sixteen"
 // namesOfIntegers now contains 1 key-value pair
 namesOfIntegers= [:]
 // namesOfIntegers is once again an empty dictionary of type Int, String


可变性

For dictionaries, immutability also means that you cannot replace the value for
an existing key in the dictionary. An immutable dictionary’s contents cannot be
changed once they are set.
Immutability has a slightly different meaning for arrays, however. You are still
not allowed to perform any action that has the potential to change the size of
an immutable array, but you are allowed to set a new value for an existing
index in the array. This enables Swift’s Array type to provide optimal
performance for array operations when the size of an array is fixed



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值