当前位置: > > > Swift - 复杂数据类型说明(数组,字典,结构体,枚举)

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

(本文代码已升级至Swift4)

一、数组 - 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个数据)

menbers.count  //获取数组元素个数
menbers.isEmpty  //判断数组是否为空

//交换元素位置(第2个和第3个元素位置进行交换)
menbers.swapAt(1, 2)

menbers.remove(at: 2)  //删除下标为2的数组
menbers.removeLast()  //删除最后一个元素
menbers.removeAll(keepingCapacity: true)  //删除数组中所有元素

let addStringArr = types + menbers //数组组合

//使用for in 实现数组遍历
for value in menbers{
    print("\(value)");
}

//通过enumerate函数同时遍历数组的所有索引与数据
for (index,value) in menbers.enumerated(){
    print("索引:\(index) 数据:\(value)");
}

//过滤数组元素
let newTypes = types.filter { $0.count < 6 } //["none", "error"]

//创建包含100个元素的数组 ["条目0", "条目1" ... "条目99"]
let items = Array(0..<100).map{ "条目\($0)"}

二、字典 - 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值
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]

2,其它几种创建字典的方法

(1)通过元组创建字典
let tupleArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27)]
let dictionary = Dictionary(uniqueKeysWithValues: tupleArray)
print(dictionary) //["Monday": 30, "Tuesday": 25, "Wednesday": 27]

(2)通过键值序列创建字典
let names = ["Apple", "Pear"]
let prices = [7, 6]
let dict = Dictionary(uniqueKeysWithValues: zip(names, prices)) //["Pear": 6,  "Apple": 7]

(3)只有键序列、或者值序列创建字典
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)字典分组(比如下面生成一个以首字母分组的字典)
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配合速记+可以用来解决重复键的问题(相同的键值相加)
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)下面使用元组创建字典时,遇到相同的键则取较小的那个值
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
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,我们可以直接指定一个默认值,如果不存在该键值时名,会直接返回这个值。下面代码的效果同上面是一样的。
let dic = ["apple": 1, "banana": 2 ]
let orange = dic["orange", default:0]
print(orange)

(3)下面是统计一个字符串中所有单词出现的次数。可以看到了有了默认值,实现起来会简单许多。
let str = "apple banana orange apple banana"
var wordsCount: [String: Int] = [:]
for word in str.split(separator: " ") {
    wordsCount["\(word)", default: 0] += 1
}
print(wordsCount)

三、结构体 - 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")  //调用逐一构造器创建实例
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())
评论5
  • 5楼
    2016-08-09 14:03
    寶寳

    楼主有视频吗?

    站长回复

    谢谢支持,这个暂时还没有。

  • 4楼
    2016-06-29 10:27
    北斗

    怎么交换数组中两个元素的位置啊

    站长回复

    可以使用内置的swap函数来实现,我文章里已经补充了。

  • 3楼
    2016-06-06 20:13
    逆境

    航哥,你好!
    我在一个类里有一个三个值的数组,我可以print出例如:stringValueArray[0]的值,但是我到另一个类里去调用这个下标为0的值的时候他就报错fatal error: Array index out of range,我数组里是有这个值的为什么会报这个错。

    站长回复

    看报错肯定是这个对象里的数组是空的,你试试在另一个类里把原来那个对象中的数组整个打印下看看:print(xxxx.stringValueArray)

  • 2楼
    2016-05-22 23:54
    大脸猫

    楼主,我遍历一个数组的时候老是报错,NSArray is ambiguous without more context 这是什么原因啊

    站长回复

    文章代码我又试了下没问题。就不知道你数组是怎么定义,还有如何遍历的。

  • 1楼
    2016-01-15 15:14
    我不是张三

    求楼主写一个类型的转换实例工具类..就是 int - string string - int 浮点等...从其他语言转换过来..这种类型转换 都是空白...
    还有就是.楼主的当前有*位在线.统计的是 session.count 吗.

    站长回复

    这个没必要写工具类,互相转换都很方便,站内有相关文章。
    1,数值型转字符串:let str = "(intValue)"
    2,字符串转数字(包括整形,浮点型):http://www.hangge.com/blog/cache/detail_698.html
    3,浮点数转换成整数:http://www.hangge.com/blog/cache/detail_708.html
    人数统计不是统计session.count,只是简单的ip数统计。