swift学习日记(二) 字符串 集合类型 控制流

来源:互联网 发布:vs2017开发unity3d 编辑:程序博客网 时间:2024/06/07 15:51

昨天看太晚了,就没写,今天一起补上


一,字符串

这个跟其他语言略有不同,不过差别也不大,基本语法一眼就会,具体的字符串操作比较多语法糖,不过可以等到做proj的时候再去深入就行了

1,支持isEmpty, +, +=, ==各种操作

2,遍历,这个有点坑

我找到的有这么几种办法

var str = "abcdefg" //在swift1中,直接用str即可遍历for character in str.characters {    //character = "6"    print(character)}


for var i = str.startIndex; i != str.endIndex; i++ { //注意,startIndex并不是int类型,按我的理解,Index类型类似于迭代器    print(str[i]) //在swift中,下标必须是Index类型,这也就造成了我们没法直接对string某一部分进行操作,
                  //而且也没法更改str[i]的值,因为在swift中,下标是"get-only"的,具体怎么实现呢,以后我再慢慢研究
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
顺便说一句,在swift中,花括号{}是必不可少的

3,计数

var count = str.characters.count

这个跟swift1也是不同的,无力吐槽,原来的

countElements(str)
被废弃了,swift真是药丸

4,swift支持用字符串格式化来生成新串

5,支持前缀后缀检查

print(str.hasPrefix("ab")) //trueprint(str.hasPrefix("b")) // falseprint(str.hasSuffix("f")) // false


6,此外,String和charactersView类型都有一些比较方便的函数,比如取某一范围的串,更改某一范围的串等,留给各位自己去发现(别说你不会找一个类有哪些子函数)

再次吐槽,swift的String我要想更改里面某一段的内容简直难上天


二,集合类型

这个上一节有讲过,继续补充

1,对字典的遍历

for (airportCode, airportName) in airports {print("\(airportCode): \(airportName)")}

用一个元组来接收

没了。。。。详情请看上一节


三,控制流

意思就是if while for

if除了判断不用括号,其他几乎完全一样,对了,花括号不能少

while同上

continue和break同上

for循环添加了个for in结构,学过PHP或者python无缝过渡,没学过的也是看一样就会

for index in 1...5 {print("\(index) times 5 is \(index * 5)")}

相对于C语言,Swift中switch语句的case语句后,不会自动跳转到下一个语句,这样就避免了C语言中因为忘记break而造成的错误。另外case语句可以匹配多种类型,包括数据范围,元组,或者特定的类型等。switch语句中已匹配的数值也可以被用在后续的case语句体中,where关键词还能被加入任意的case语句中,来增加匹配的方式。


let someCharacter: Character = "e"switch someCharacter {case "a", "e", "i", "o", "u":print("\(someCharacter) is a vowel")case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m","n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":print("\(someCharacter) is a consonant")default:print("\(someCharacter) is not a vowel or a consonant")}

此外,switch还可以匹配范围,元组,还可以绑定

let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0):print("on the x-axis with an x value of \(x)")case (0, let y):print("on the y-axis with a y value of \(y)")case let (x, y):print("somewhere else at (\(x), \(y))")}

还可以添加where关键词

let yetAnotherPoint = (1, -1)switch yetAnotherPoint {case let (x, y) where x == y:print("(\(x), \(y)) is on the line x == y")case let (x, y) where x == -y:print("(\(x), \(y)) is on the line x == -y")case let (x, y):print("(\(x), \(y)) is just some arbitrary point")}

swift还多了一个fallthrough

由于Swift中的switch语句不会自动的因为没有break而跳转到下一个case,因此如果需要想C语言中那样,依次执行每个case的时候,就需要用到fallthrough关键词。


然后就没了


这次完了,转到下次




0 0
原创粉丝点击