swift学习笔记5

五、集合

数组

1、泛型 Array<类型>

2、简化[类型]

var myAr:Array<String>

var names:[String]

myArr = Array<String>()

names = Array<String>(count:10,repeatedValue:"heri")

nums = Array<Int>(count:100,repeatedValue:0)

var values = ["2","3","4","o"]

println(names[1])

name[0]="spring"

for var i=0;i <values.count;i++

{
println(values[i])

}

for v in values

{
println(v)

}

添加元素

var languages = ["swift"]

languages.append("Go")

languages +=["Ruby"]

插入元素

languages.insert("R",atIndex:0)

let subRange = languages[1..<4]

languages[2...4] = ["c++","php"]

清空

languages[0..<languages.count] = []

删除

languages.removeAtIndex(2)

languages.removeLast()

languages.removeAll()

字典

1、泛型 

2、简化

var myDict : Dictionary<String,String>

var health:[String,String]

构造器

myDict = Dictionary<String,String>()

health = ["身高":"180","体重":"70","血压":"90/120"]

读取 var height = health["身高"]

var emptyDict :[String:Double]=[:]

health["体重"]= 80

添加新的key - value对

var result = health.updateValue("50",forkey:"腰围")

desc 默认代表 value

var seasons = ["spring":"春暖花开","summer":"夏日炎炎"]

for (season,desc)in seasons

{

println("\(season) -->\(desc)")

}

var keys = Array(seasons.keys)

var values = Array(seasons.values)

删除

var languages = ["swift":900,"php":340,"oc":48]

languages.removeValueForKey("php")

languages["oc"]=nil

languages.removeAll()

实战例子: 记录字符串中每个字符出现的次数,并且对比哪个出现最多

let str = "renhairui is a best man xhahahaxxxxx"

var status :[Character:Int] =[:]

for ch in str

{

if num !=nil

{

var num = status[ch]

status[ch] = num! +1

}else{

status[ch] = 1

}

}

println(status)

var maxOccurs = 0

for occurs in Array(status.values)

{

if occurs >maxOccurs

{

maxOccurs = occure

}

for (ch,occurs)in status

{

if occurs == maxOccurs

{

println("出现最多的字符:\(ch),出现次数:\(occurs)次")

}

}

 

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。