常量 变量
let age = 20 常量不可变
var num = 24 变量可变
let count:Int = 2 定义类型
Double(count) 类型转换
符号
1.??
let def = "red"
var user : String?
user = "hh"
user ?? def
2.(a...b
)
for index in 1...5 {
print("(index) times 5 is (index * 5)")
}
3. (a..<b
)
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person (i + 1) is called (names[i])")
}
字符串
let name:String = "hrrrrrrrrr"
var addr:String = String()
print(name)
print("my name is (name)")
Swift的String操作比较复杂,经常转为oc 的NSString
(name as NSString).substringToIndex(5)
(name as NSString).substringWithRange(NSMakeRange(5, 2))
(name as NSString).length
也可以不转直接操作
1.isEmpty
if emptyString.isEmpty {
print("Nothing to see here")
}
2.遍历字符串
for character in "Dog!".characters {
print(character)
}
3.字符串添加
string1 += string2
string1.append(string2)
4.atIndex
let greeting = "Guten Tag!"
greeting[greeting.startIndex]第一个// G
greeting[greeting.endIndex]错的错的
greeting[greeting.index(before: greeting.endIndex)]最后一个// !
greeting[greeting.index(after: greeting.startIndex)]第二个// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]// a
5.indices index集合
for index in greeting.characters.indices {
print("(greeting[index]) ", terminator: "")
}
6.insert
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex))
7.hasPrefix(_:)
hasSuffix(_:)
是否存在(开头,存在)