swift学习笔记2-串、循环、分支语句

来源:互联网 发布:淘宝水军平台 编辑:程序博客网 时间:2024/05/22 02:30

1.学过swift语言的,一定会为里面的串感到惊奇。在swift语言中,串可以直接比较,不像C语言,还需要调用相关的函数,这和java有相同之处。swift语言中,串是可以直接使用“+”运算符进行进行连接的。对与不同类型数据,swift也给出了如何将至连接到串中,好用的超乎你想象

//串的定义var a = "hello swift"var b = "hello world"//串的逻辑比较print(a==b)//串的连接a = a + bprint(a) //输出 hello swifthello worldvar c = a+bvar d = 10c = "\(d)\(c)"//输出 10 hello swifthello worldprint(c)c.append(b)print(c)//输出 10 hello swifthello worldhello world


2.从swift3.0开始,swift语言抛弃了object-c中for循环的写法。只能使用 for in循环

c = "hello"for char in 0..<c.characters.count {//遍历字符串    print(char)//输出 hello}var sum = 0for a in 1...10{    sum = sum + a//计算 1-10 的和}print(sum) // 输出55for b in 1..<10{    if(b < 5){        print(b)    }}var times = 0while times < 5 {    times += 1    print(times)}repeat{    print(times)    times -= 1}while(times > 0)


3.swift语言的分支语句switch不需要添加break,系统根据条件进入指定的分支中,然后推出。swift提供了更复杂的条件匹配模式。十分灵活。swift语言中也有continue,和C用法一致。

switch times {case 1:    print("times = 1")case 2,3,4:    print("2<=times<=4")case let index where index>5 && index<10:    print(".....")case 11...15:    print(".....")default:    print("other")}