数组、字典、字符串都比oc省略了“@”
数组
var arr:Array = [1,2,3,4]
//遍历数组
for number in arr
{
print(number)
}
//数组增加
arr.append(5)
//数组的排序
let sortArr = arr.sort { (first, second) -> Bool in
return first>second //(有大到小排序)
}
print(sortArr)
//数组的删除
arr.removeFirst() //删除第一个
arr.removeLast() //删除最后一个
arr.removeAtIndex(1) //删除索引为1的
arr.removeAll() //删除全部
字典
//创建字典
var dict:Dictionary = ["name":"xiaoming","age":4]
//获取value
var nameStr = dict["name"]
//遍历字典 会把key赋值第一个参数,value赋值第二参数
for(key,value) in dict
{
print(key)
print(value)
}
//增加key/value
dict["gender"]="男"
//更新key/value
dict["age"] = 10
//删除
//dict.removeAll() //删除全部
dict.removeValueForKey("gender")
//合并字典
var dict2 = ["height":150]
for(key,value) in dict2
{
dict[key] = value
}
字符串
//字符串的初始化
var str:String = "hellow Swift"
var str2 = "222"
//字符串的拼接和格式化
str += str2
let number = 100
let name = "你刚回来了"
//拼接其他类型
var str3:String = "name = \(name),age = \(number)"
//oc形式的拼接方法
var str4 = String(format: "%@,%@", arguments: ["xiao","ming"])
//字符串额截取(字符串和oc的字符串可以无缝连接)
//装换oc的字符串可以使用oc的一些截取的方法
var str5:NSString = "你刚回来了"
var str6 = "你刚回来了" as NSString
var substr = str6.substringWithRange(NSMakeRange(0, 4))
//swift的字符的截取
var str7 = "你刚回来了234567890"
// let index = advance(s.startIndex, 5) swift 1.x
//let index2 = advance(s.endIndex, -6); swift 1.x
let index = str7.startIndex.advancedBy(5) //swift 2.0+
let index2 = str7.endIndex.advancedBy(-2) //swift 2.0+
var range = Range<String.Index>(start: index,end: index2)
//从什么地方开始截取(从index开始,不包含index的字符)
var subStr1 = str7.substringFromIndex(index);
//从0开始截取 到字符串中长度的减6的位置结束(不包含index2)
var subStr2 = str7.substringToIndex(index2);
//从index的位置到index2的位置(不包含index和index2的位置)
var substr3 = str7.substringWithRange(range);
//遍历字符
for c in str4.characters
{
print(c)//从什么地方开始截取(从index开始,不包含index的字符)
}