5、集合php
數組c++
一、泛型 Array<類型>spring
二、簡化[類型]swift
var myAr:Array<String>數組
var names:[String]app
myArr = Array<String>()ui
names = Array<String>(count:10,repeatedValue:"heri")spa
nums = Array<Int>(count:100,repeatedValue:0)rem
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()
字典
一、泛型
二、簡化
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)次")
}
}
}