基于版本:4.1.2
运算符
- 赋值
let a = 2
- 操作符
a + b a += a //swift4 废弃++ a +=2 a * b a / b //b不能为0 a % b // b 不能为0 let d = 5.2,e = 1.7 d / e d % e //也能使用浮点型进行求余 Int.max //查看Int类型支持的最大值 Int.min //查看Int类型支持的最小值 var c = 2 c+=1 //条件运算符 var score = 62 var rate = score > 60 ? "合格":"不合格"
- nil聚合运算符
var userNickName :String? userNickName = "imagine" let outputName:String = userNickName != nil ? userNickName! : "Guest" print("hello,"+outputName) //改进 let outputName:String = userNickName ?? "Guest"
- 区间运算符
//闭区间 [a,b] 表示:a...b //前闭后开区间 [a,b) 表示:a..<b
- for-in
for index in 1..<10 { index //index = 3 //error } //arr.count数组长度 let names = ["aaa","bbb","ccc"]; for i in 0..<names.count { names[i] }
- 逻辑运算符
!a //非 a && b //与 a || b //或 区别“位运算符” a & b //按位与 a | b //按位或
字符串
- String和Character
//变量与常量字符串 var str1 = "aaa" let str2 = "bbb" //创建空字符串 var emptyString = "" var str2 = String() //字符串遍历 var str = "hello" for c in str { print(c) } //定义一个字符 var ch:Character = "!" str.append(ch) //在字符串后面拼接一个字符 //字符串之间拼接 var str2 = "!!!" str += str2 //hello!!!!
- String操作
var str = "Hello" //拼接 str + "imagine" str str += "imagine" str //字符串插值 print("123 \(str)") //字符串比较 //按字典顺序比较,不考虑长度 let str_a = "abc" let str_b = "abc" str_a == str_b let str_c = "abd" str_a < str_c //前缀 Prefix 与 后缀 Suffix //.hasPrefix and .hasSuffix //统计前缀有 b 的个数 let names = [ "a 1.aaa", "b 1.bbb", "b 2.bbb", "b 3.ccc" ] var count = 0 for name in names { if name.hasPrefix("b"){ count += count //3 times } }
- 导入Foundation 使用字符串的更多功能
import Foundation var str = "hello" str.capitalized //Hello 首字母大写 str.uppercased() //字母大写 str.lowercased() //字母小写 //split var str2 = "hello hhh" str2.components(separatedBy: " ")