Swift2.0学习一
Swift2.0学习一基本类型整型
使用下划线对很多的数进行分割,以方便阅读 类型转换 let x: UInt16 = 100 let y: UInt8 = 20 let m = x + UInt16(y) let n = UInt8(x) + y 元祖
如下 let point3 = (x: 3,y: 2) point3.x let point4: (x: Int,y: Int) = (10,5) point4.x 如果对元祖的某个分量不感兴趣,可以使用下划线 let loginResult = (true,"data") let (isLoginSuccess,_) = loginResult print let x = 1,y = 2,z = 3 print(x,y,z,separator: "---") print(x,separator: "+++",terminator: ":)") 运算符区间运算符 闭区间运算符[a,b] 控制流循环结构 for _ in 1...power { result *= base } C风格的循环 var index = -99 var step = 1 for ; index <= 99; index += step { index * index step *= 2 }
for i in 10.stride (through: 0,by: -1) { print("(i)") }
switch let vector = (1,1) switch vector { case(0,0): print("It,s origin!") case(1,0): print("1 0") case(1,1): print("1 1") default: print("default") }
如下 let point = (0,0) switch point { case (0,0): print("It's origin!") fallthrough case (_,0): print("It's on the x-axis") case(0,_): print("It's on the y-axis") default: print("It's just an ordinary point.") } 控制转移 findAnswer:for m in 1...300 { for n in 1...300 { if m*m*m*m - n*n == 15*m*n { print(m,n) break findAnswer } } } where 与模式匹配 let age = 19 if case 10...19 = age { print("You're a teenager") } 其后还可以跟where if case 10...19 = age where age >= 18 { print("You're a teenager") } 同样可以在for循环中使用where语句,如下 for i in 1...100 { if i%3 == 0 { print(i) } } for case let i in 1...100 where i % 3 == 0 { print(i) } guard func buy(money: Int,price: Int,capacity: Int,volume: Int) { if money >= price { if capacity > volume { print("I can buy it!") print("(money-price) Yuan left.") print("(capacity-volume) cubic meters left") }else{ print("Not enough capacity") } }else{ print("Not enough money") } } 使用 func buy2(money: Int,volume: Int) { guard money >= price else { print("Not enough money") return } guard capacity >= volume else { print("Not enough capacity") return } print("I can buy it!") print("(money-price) Yuan left.") print("(capacity-volume) cubic meters left") } 字符串遍历字符串中所有的字符 var str = "Hello,swift" for c in str.characters { print(c) } 获取字符串字符的长度 var chineseLetters = "权力的游戏" chineseLetters.characters.count String.Index和Range var str = "Hello,swift" let startIndex = str.startIndex str[startIndex.advancedBy(5)]
let spaceIndex = startIndex.advancedBy(6) str[spaceIndex.predecessor()]
str[spaceIndex.successor()]
使用Index组成区间 let range = startIndex..<spaceIndex.predecessor() 一些用法 str.replaceRange(range,with: "Hi") str.appendContentsOf("!!!") str.insert("?",atIndex: str.endIndex) as 和 NSString
let s2: String = NSString(format: "one third is %.2f",1.0/3.0) as String
let s6 = " ---- Hello ------- " as NSString s6.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " -")) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |