OC
和Swift
中字符串的区别 OC
中字符串类型时NSString
,在Swift中
字符串类型是String
OC
中字符串@""
,Swift
中字符串""
String
的原因 NSString
是一个OC
对象,性能略差String
支持直接遍历Swift
提供了String
和NSString
之间的无缝转换 let string = "I am you"
for character in string.characters {
print(character)
}
let string1 = "city "
let string2 = "of "
let string3 = "stars"
let song = string1 + string2 + string3
print("\(song) by Ryan Gosling")
let age = 48
let name = "Matthew"
let height = 1.85
let info = "my name is \(name), age is \(age), height is \(height)"
print(info)
let minute = 13
let second = 04
let hour = 11
let timeString = String(format: "%02d:%02d:%02d", arguments: [hour,minute, second])
print(timeString)
Swift
中提供了特殊的截取方式 Index
创建较为麻烦String
转成NSString
来使用 :as NSString
即可let songString = "closer to me"
// 将String类型转成NSString类型 string as NSString
let header = (songString as NSString).substring(to: 6)
let middle = (songString as NSString).substring(with: NSRange(location: 7, length: 2))
let footer = (songString as NSString).substring(from:10)
print("header:\(header) middle:\(middle) footer:\(footer)")
let song = "Traveling Light"
let firstCharacter = song.characters.index(of: "i")!
let string = String(song.characters.prefix(upTo: firstCharacter))
print(string)
// 定义一个可变数组,必须初始化才能使用
var array : [String] = [String]()
// 定义一个不可变数组
let names : [String] = ["Jennifer", "David"]
var arrayM1 = Array<String>()
var arrayM2 = [String]()
// 定义时直接初始化
var arrayM = ["Jennifer", "Courteney", "David"]
// 先定义,后初始化
var arrayM : Array<String>
array = ["Jennifer", "Courteney", "David"]
// 给数组创建10个相同的元素
var digitCounts = Array(repeating: 0, count: 10)
arrayM.append("Matt")
arrayM.remove(at:0)
arrayM[1] = "Ben"
// 可变和不可变数组通用
array[0]
arrayM[0]
// 遍历数组
for i in 0..print(arrayM[i])
}
// for in方式
for name in arrayM {
print(name)
}
// 设置遍历的区间
for name in array[0..<2] {
print(name)
}
for i in 0..<2 {
print(arrayM[i])
}
// 反序遍历
for name in array.reversed() {
print(name)
}
// 数组合并
var array = ["Jennifer", "Courteney","Matt"]
var array1 = ["David", "Matthew"]
var array2 = array + array1;
Swift 的Dictionary类型被桥接到Foundation的NSDictionary类。
Swift
的字典使用Dictionary
定义,其中Key是字典中键的数据类型,Value是字典中对应于这些键所存储值的数据类型。
注意:字典的Key类型必须遵循Hashable协议
我们也可以用[Key: Value]
这样简化的形式去创建一个字典类型。虽然这两种形式功能上相同,但是后者是首选。
// namesOfIntegers 是一个空的 [Int: String] 可变字典
var namesOfIntegers = [Int: String]()
// 定义一个不可变字典
let dict = ["name" : "Chandler"]
// 添加数据
dict["phoneNumber"] = "+86 110"
dict["girlFriend"] = "Monika"
// 删除字段
dict.removeValue(forKey: "phoneNumber")
// 修改字典
dict["name"] = "Joey"
// 查询字典
dict["name"]
// 元组的基本写法
let userInfo = ("Matthew", 48, 1.85)
userInfo.0
userInfo.1
userInfo.2
// 给每一个元素起别名
let userInfo1 = (name : "Matthew", age : 48, height : 1.85)
userInfo1.name
userInfo1.age
userInfo1.height
// 别名就是变量的名称
let (name, age, height) = ("Matthew", 48, 1.85)
name
age
height