判断
if判断 普通条件判断
func demo2(){
let url = NSURL(string: "www.baidu.com")
//if判断url 可选类型有没有值
if url != nil {
let request = NSURLRequest(URL: url!)
print(request)
}
}
//if let 判断可选类型 有值才执行 没值就不执行
func demo3(){
let url = NSURL(string: "www.baidu.com")
if let u = url{
let request = NSURLRequest(URL: u)
print(request)
}
}
//if let 多个可选类型判断
func demo4(){
let name: String? = "张三"
let age: Int? = 20
if let n = name,a = age{
print("\(n)\(a)")
}
}
//guard let 判断可选类型常量变量有没有值 有则赋值给定义的常量或者变量 如果没有则执行else语句
func demo5(){
let url = NSURL(string:"www.baidu.com")
//guard let判断
guard let u = url else{
print("url 为nil")
return
}
let request = NSURLRequest(URL: u)
print(request)
}
//if let 后边跟where语句
func demo6(){
let url = NSURL(string: "http://www.baidu.com")
//if let 判断url 存在 where条件 域名是不是百度
if let u = url where u.host == "www.baidu.com"{
//再次判断 u.host的可选类型
if let s = u.host{
let request = NSURLRequest(URL: u)
print(request)
print(s)
}
}
}
//if let 多个参数 where语句判断
func demo7(){
let name:String? = "张三"
let age:Int? = 20
if let a = name,u = age where a == "张三" && u == 20{
print(a,u)
}
}
// switch 判断
/*
swift
可以判断任意类型
可以省略break
是可以省略大括号'{}'
case 后面一定要有执行语句
func demo9(){
let score:Int? = 93
guard let num = score else{
print("nil")
return
}
switch num{
case let x where x > 90:
print("sf")
default:
print("s")
}
}
//switch
func demo8(){
let scoreStr:String? = "良"
guard let u = scoreStr else{
print("nil")
return
}
switch u{
case "优":
print(u)
case "良":
print(u)
default:
print("差劲")
}
}