swift 语法、循环

    xiaoxiao2021-03-26  30

    //: Playground - noun: a place where people can play //1.swift中如何导入框架 import UIKit //------------------------------swift中if的用法------------------------- //1>if后面的()可以省略 //2>判断语句不再有非0/nil即真,判断语句必须有明确的真假(Bool-->true/false) let a : Int = 10 if a>0 { print("a大于0") }else{ print("a小于等于0") } //2.----------------------------swift中else if的用法------------------------- //用法和if用法一致 let score = 70 if score < 0 || score > 100{ print("不合理的分数") }else if score < 60{ print("不及格") }else if score < 80{ print("及格") }else if score < 90{ print("良好") }else if score < 100{ print("不错哦") } //3.----------------------------swift中三目运算符的用法------------------------- let m = 20 let n = 30 let result = m > n ? m :n //4.----------------------------swift中guard的用法------------------------- /*guard是swift2.0新增的语法,只能在函数中使用,可以增强程序的可读性,避免过多if嵌套 *它与if语句非常类似,它设计的目的是提高程序的可读性 *guard语句必须带有else语句,它的语法如下: *1>当条件表达式为true的时候跳过else语句中的内容,执行语句组内容 *2>条件表达式为false的时候执行else语句中的内容,跳转语句一般是return、break、continue和throw * guard 条件表达式 else { //条件语句 break } 语句组 */ let age : Int = 20 //年龄 let IDCard : Bool = true //是否带了身份证 let monery : Bool = true //是否带了钱 //在一下函数内使用guard func online(age : Int){ guard age >= 18 else { print("不可以上网,回家找妈妈") return } guard IDCard == true else { print("不可以上网,回家带身份证") return } guard monery == true else { print("不可以上网,回家带钱去吧") return } print("可以留下上网,撸起来吧") } //调用函数 online(age: age) //4.----------------------------swift中switch的用法------------------------- //4.1switch的简单用法 let sex = 0 //0:男 1:女 //switch后面的() 可以省略 //case语句结束后,break也可以省略,并且不会产生case穿透。如果想产生case穿透效果,添加fallthrough语句 //case后面可以判断多个条件用逗号分割 switch sex { case 0: print("男") case 1: print("女") default: print("其他人") } //4.2 swift中的特殊用法 //4.2.1 switch可以判断浮点型 let pi = 3.14 switch pi { case 3.14: print("该小数是3.14") default: print("该小数是3.14以外的其它小数") } //4.2.2 switch可以判断字符串 let i = 30 let j = 20 let add : String = "+" switch add { case "+": print(i + j) default: print("不是加法") } //4.2.3 switch可以判断区间 //区间 (1)开区间 0..<20 表示0~19 (2)闭区间 0...20 表示0~20 let results = 88 switch results { case 0..<60: print("不及格") case 60..<80 : print("及格") case 80...100 : print("优秀") default: print("不合理分数") } //5.-------------------------swift中for in 循环的用法------------------------- for z in 0...10 { print(z) } //在swift中如果一个标识符不需要使用,可以使用_来代替 for _ in 0...9 { print("hello world") } //6.-------------swift中while 和 do while循环的用法---------------------- //while后面的()可以省略 , while后面的判断没有非0即真 var l = 10 while l > 0 { print(l) l -= 1 } //swift中do while 循环需要用 repeat while 代替 repeat { l+=1 print(l) }while l<10
    转载请注明原文地址: https://ju.6miu.com/read-350354.html

    最新回复(0)