Swift - 复杂数据类型说明(数组,字典,结构体,枚举)

一、数组 - Array

var types = ["none","warning","error"]  //省略类型的数组声明
 
var menbers = [String]() //声明一个空数组
 
menbers.append("six")  //添加元素
menbers += ["seven"] //添加元素
menbers.insert("one", at:0)  //指定位置添加元素
 
menbers[0] = "message"  //通过下标修改数组中的数据
menbers[0...2] = ["message","hangge","com"]  //通过小标区间替换数据(前3个数据)// @alphaZ
 
menbers.count  //获取数组元素个数
menbers.isEmpty  //判断数组是否为空
 
//交换元素位置(第2个和第3个元素位置进行交换)
menbers.swapAt(1, 2) // @alphaZ
 
menbers.remove(at: 2)  //删除下标为2的数组
menbers.removeLast()  //删除最后一个元素
menbers.removeAll(keepingCapacity: true)  //删除数组中所有元素
 
let addStringArr = types + menbers //数组组合
 
//使用for in 实现数组遍历
for value in menbers{
    print("\(value)");
}
 
//通过enumerate函数同时遍历数组的所有索引与数据 // @alphaZ
for (index,value) in menbers.enumerated(){
    print("索引:\(index) 数据:\(value)");
}
 
//过滤数组元素
let newTypes = types.filter { $0.count < 6 } //["none", "error"] // @alphaZ

二、字典 - Dictionary(即键值对)

1,基本用法

var empty = [String: Int]()  //建立个空字典
 
var myDic = ["name":"hangge",
             "url":"hangge.com"]  //声明一个字典
 
myDic["address"] = "china" //添加或修改key值
myDic.removeValue(forKey: "name")  //删除"name"这个key值
myDic["name"] = nil  //同样可以删除"name"这个key值// @alphaZ
myDic.keys  //访问字典的key集合
myDic.values //访问字典的values集合
 
//遍历字典
for (key,value) in myDic {
    print("\(key):\(value)");
}
 
//只遍历字典的键(key)
for key in myDic.keys {
    print("\(key)");
}
 
//只遍历字典的值(value)
for value in myDic.values {
    print("\(value)");
}
 
//过滤字典元素
let dict2 = dict.filter { $0.value < 7 } //["Pear": 6] // @alphaZ

2,其它几种创建字典的方法
(1)通过元组创建字典// @alphaZ

let tupleArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27)]
let dictionary = Dictionary(uniqueKeysWithValues: tupleArray)
print(dictionary) //["Monday": 30, "Tuesday": 25, "Wednesday": 27]

(2)通过键值序列创建字典// @alphaZ

let names = ["Apple", "Pear"]
let prices = [7, 6]
let dict = Dictionary(uniqueKeysWithValues: zip(names, prices)) //["Pear": 6,  "Apple": 7]

(3)只有键序列、或者值序列创建字典// @alphaZ

let array = ["Monday", "Tuesday", "Wednesday"]
let dict1 = Dictionary(uniqueKeysWithValues: zip(1..., array))
let dict2 = Dictionary(uniqueKeysWithValues: zip(array, 1...))
print("dict1:\(dict1)")
print("dict2:\(dict2)")

(4)字典分组(比如下面生成一个以首字母分组的字典)// @alphaZ

let names = ["Apple", "Pear", "Grape", "Peach"]
let dict = Dictionary(grouping: names) { $0.first! }
print(dict) //["P": ["Pear", "Peach"], "G": ["Grape"], "A": ["Apple"]]

3,重复键的处理
(1)zip配合速记+可以用来解决重复键的问题(相同的键值相加)// @alphaZ

let array = ["Apple", "Pear", "Pear", "Orange"]
let dic = Dictionary(zip(array, repeatElement(1, count: array.count)), uniquingKeysWith: +)
print(dic) // ["Pear": 2, "Orange": 1, "Apple": 1]

(2)下面使用元组创建字典时,遇到相同的键则取较小的那个值// @alphaZ

let duplicatesArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27), ("Monday", 28)]
let dic = Dictionary(duplicatesArray, uniquingKeysWith: min)
print(dic) // ["Monday": 28, "Tuesday": 25, "Wednesday": 27]

4,字典合并
想要将一些序列、或者字典合并到现有的字典中,可以借助如下两个合并方法:
merge(: uniquingKeysWith:):这种方法会修改原始Dictionary
merging(
: uniquingKeysWith:):这种方法会创建并返回一个全新的Dictionary // @alphaZ

var dic = ["one": 10, "two": 20]
 
//merge方法合并
let tuples = [("one", 5),  ("three", 30)]
dic.merge(tuples, uniquingKeysWith: min)
print("dic:\(dic)")
 
//merging方法合并
let dic2 = ["one": 0, "four": 40]
let dic3 = dic.merging(dic2, uniquingKeysWith: min)
print("dic3:\(dic3)")

5,默认值
(1)过去我们如果希望当某个字典值不否存在时,使用一个指定的默认值,这个通常会使用if let来判断实现。

let dic = ["apple": 1, "banana": 2 ]
var orange:Int
if let value = dic["orange"] {
    orange = value
}else{
    orange = 0
}
print(orange)

(2)到了 Swift4,我们可以直接指定一个默认值,如果不存在该键值时名,会直接返回这个值。下面代码的效果同上面是一样的。// @alphaZ

let dic = ["apple": 1, "banana": 2 ]
let orange = dic["orange", default:0]
print(orange)

(3)下面是统计一个字符串中所有单词出现的次数。可以看到了有了默认值,实现起来会简单许多。// @alphaZ

let str = "apple banana orange apple banana"
var wordsCount: [String: Int] = [:]
for word in str.split(separator: " ") {
    wordsCount["\(word)", default: 0] += 1
}
print(wordsCount)

// ["apple": 2, "orange": 1, "banana": 2]

三、结构体 - struct

//创建一个结构体
struct BookInfo{
    var ID:Int = 0
    var Name:String = "Defaut"
    var Author:String = "Defaut"
}
 
var book1:BookInfo //默认构造器创建结构体实例
var book2 = BookInfo(ID:0021,Name:"航歌",Author:"hangge")  //调用逐一构造器创建实例 // @alphaZ 编译器默认自动创建逐一构造器
book2.ID = 1234  //修改内部值

四、枚举 - enum

enum CompassPoint {
    case north
    case south
    case east
    case west
}
var directionToHead = CompassPoint.west
 
enum Planet: Int {
    case mercury = 1
    case venus = 2
    case earth = 3
}
let earthsOrder = Planet.earth.rawValue //rawValue来获取他的原始值:3
let possiblePlanet = Planet(rawValue: 2)  //通过原始值来寻找所对应的枚举成员:Venus
 
enum Direction {
    case up
    case down
     
    func description() -> String{
        switch(self){
        case .up:
            return "向上"
        case .down:
            return "向下"
        }
    }
}
print(Direction.up.description())

(本文代码已升级至Swift4)

原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_515.html

你可能感兴趣的:(Swift - 复杂数据类型说明(数组,字典,结构体,枚举))