一、字符串
1.定义字符串
let name:String = "jack"//不可变字符串
var age = "12"//可变字符串
在OC中字符串类型时NSString,在Swift中字符串类型是String;
OC中字符串@””,Swift中字符串””String 是一个结构体,性能更高
NSString 是一个 OC 对象,性能略差
2.获取字符串的长度
age.count
3.字符串的拼接
var strM = "str"
strM=strM.appending("M")
let str1 = "qqqqq"
let str2 = "aaaaa"
let str = str1+str2
let weight = "64kg"
let height = "1.77m"
let description = "I have\(weight)weight,have\(height)height"
let min = 3
let second = 4
let time = String(format: "%02d:%02d", arguments: [min, second])
4.字符串的截取
Swift中Swift中提供了特殊的截取方式,但创建较为麻烦通过,我们可以通过as关键字可以将String类型转成NSString的类型
let urlString = "abcdefghhhh"
let a = (urlString as NSString).substring(to: 3)
let b = (urlString as NSString).substring(from: 10)
let c = NSRange(location: 4, length: 5)
let d = (urlString as NSString).substring(with: range1)
二、数组
Swift 数组的类型完整写法是 Array<Element>, Element是数组允许存入的值的类型。你同样可以简写数组的类型为 [Element],在开发中更推荐使用[Element]这种语法。
1.定义数组
let array0:Array<String> = ["1","2"]//定义方式一
let array:[String] = ["1","2"]//定义方式二 常用方式
let array1 = ["3"]//类型推导
let array2 = [1,"2",1.24] as [Any]//泛型集合
let view = UIView()
let array3:[Any] = [1,"2",view]//泛型集合
var array0M:Array<String> = ["1","2"]
var arrayM:[String] = ["1","2"]
2.初始化一个空数组
var array1M:Array<String> = Array()
var array3M = [String]()//常用方式
var array2M = Array<String>()
3.对数组的增、删、改、查
array2M.append("1111")
array2M.append("2222")
array2M.append("3333")
array2M.removeFirst()
array2M.remove(at:1)
array2M
array2M[0] = "name"
array2M[0]
4.遍历数组的方式
//区间遍历
for i in 0..<array.count {
print(array[i])
}
//获取item
for item in array{
print(item)
}
//获取item,并设置遍历区间
for item in array[0..<2] {
print(item)
}
//同时获取索引和item
for (index, name) in array2.enumerated() {
print(index)
print(name)
}
5.数组合并(只有相同类型的数组才能这样合并)
var a = ["1"]
var a1 = ["2"]
var a2 = array + array1;
三、字典
Swift 的字典类型写全了是这样的: Dictionary<Key, Value>,其中的 Key是用来作为字典键的值类型, Value就是字典为这些键储存的值的类型。你同样可以用简写的形式来写字典的类型为 [Key: Value]。在开发中更推荐使用 [Key: Value]这种语法。
1.定义字典
let dic:Dictionary<String,String> = ["name":"jack"]//定义方式一
let dict2 : [String : Int] = ["age" : 18]//定义方式二 常用方式
let dict3 = ["age" : 18]//定义方式二 常用方式//类型推导
2.初始化一个空字典
var dict4 : Dictionary<String,String> = Dictionary()
var dict6 = Dictionary<String,String>()
var dict5 :[String:String] = [String:String]()
var dict7 = [String:String]()// 常用方式
3.字典的增删改查
// 增加
dict7["name"] = "jack"
dict7["skill"] = "sing"
// 查询
dict7["name"]
// 修改
dict7["name"] = "zzz"
dict7.updateValue("hlt", forKey: "jack")
// 删除
dict7.removeValue(forKey: "name")
4.遍历字典
// 遍历字典中所有的key
for value in dict7.values {
print(value)
}
// 遍历字典中所有的value
for key in dict7.keys {
print(key)
}
// 遍历所有的value,key
for (key, value) in dict7 {
print(key)
print(value)
}
四、元组
元组仍然是一个变量,可以存储 N个 任意类型的数据
写法一:
let Tuple= ("hat", 18, 1.88)
let name = Tuple.0
let age = Tuple.1
写法二:
let Tuple= (name : "hhhh",age : 18, height : 1.88)
print(Tuple.age)
print(Tuple.height)
print(Tuple.name)
写法三:
let (name, age, height) = ("qqq", 18, 1.88)
print(name)
print(age)
print(height)
网友评论