swift基础介绍-1

2016-12-03  本文已影响8人  7dfa9c18c1d1

1、常量和变量
常量:

变量:

2、swift中的类型推导

let a : Int = 1 // 完整的写法,a的数据类型是Int
let a1 = 1 // 通过类型推导,a1的数据类型是Int

3、swift中基本运算

let b = 2
let b2 = 3
print(b+b2) // 数据类型一致,可以运算
let b3 = 4.1
print(b+b3) // 直接报错,因为数据类型不一致

4、swift中的逻辑分支

let c = 10
//if c {
//    print(c) // 错误写法:条件判断句必须true/false
//}
// 正确写法是
if c > 10 {
    print(c)
}
let d = 0
switch d {
case 0: // 省略了()
    print("是数字0") //可以不用跟break
    fallthrough // 加上这个关键字,则这个case有穿透效果,会打印(是数字1,2,3);去掉这个关键字,则不打印(是数字1,2,3)
case 1,2,3: // 可以跟多个判断值
    print("是数字1,2,3")
case 4:
    print("是数字4")
default:
    print("其他")
}

// 支持浮点型
let d2 = 3.14
switch d2 {
case 3.14:
    print(d2)
default:
    print("other")
}

// 支持字符串型
let d3 = "+"
switch d3 {
case "+":
    print("加号")
case "-":
    print("减号")
case "/":
    print("除号")
case "*":
    print("乘号")
default:
    print("other")
}

// 支持区间
let score = 88
switch score {
case 0..<60:
    print("不及格")
case 60..<90:
    print("良好")
case 90...100:
    print("优秀")
default:
    print("other")
}
guard 条件判断句 else {
// 当条件表达句是false是的时候,执行这里的代码
// 这里一般常跟 break 、continue (一般出现在循环中)
// return (一般出现在函数中)
 }
func online(age : Int) {
    guard age >= 18 else {
        print("年龄太小,不能上网")
        return
    }
    print("可以上网")
}
for i in 0 ..< 10 {
    
}

//如果在循环中不用下标i,可以使用`_`代替
for _ in 0 ..< 10 {
    
}
上一篇 下一篇

猜你喜欢

热点阅读