美文网首页程序员
Swift中where的用法总结

Swift中where的用法总结

作者: Andy_Ron | 来源:发表于2017-11-09 12:28 被阅读836次

不同的版本的Swift中where用法有些不同,以最新的Swift4为准,

  1. if, guard, while三个语句中where被去掉了,直接使用,相隔就行了
if let oldMan: Int = 50, let youngerMan: Int = 18, oldMan > youngerMan {
    print("odlMan > youngerMan")
} else {
    print("错误判断")
}

var arrayTwo:[Int]? = []
while let arr = arrayTwo, arr.count < 5 {
    arrayTwo?.append(1)
}

let string:String? = "小刚"
guard let str = string, str != "小明" else {
    fatalError("看错人了") //
}
print("确实是小明")
  1. do catch
enum ExceptionError:Error{
    case httpCode(Int)
}
func throwError() throws {
    throw ExceptionError.httpCode(500)
}
do{
    try throwError()
}catch ExceptionError.httpCode(let httpCode) where httpCode >= 500{
    print("server error")
}
  1. switch
var value:(Int,String) = (1,"小明")
switch value {
case let (x,_) where x < 60:
    print("不及格")
default:
    print("及格")
}
  1. for in
let arrayOne = [1,2,3,4,5]
let dictionary = [1:"hehe1",2:"hehe2"]
for i in arrayOne where dictionary[i] != nil {
    print(i)
}
  1. 泛型
func genericFunction<S>(str:S) where S:ExpressibleByStringLiteral{
    print(str)
}
// 也可以不使用where语句,直接在尖括号中定义时做限制
func genericFunction2<S:ExpressibleByStringLiteral>(str:S){
    print(str)
}
  1. 协议
protocol aProtocol{}
extension aProtocol where Self:UIView{
    //只给遵守myProtocol协议的UIView添加了扩展
    func getString() -> String{
        return "string"
    }
}

playground文件:andyRon/LearnSwift/Where.playground

参考:
Swift where 关键字

相关文章

  • Swift中where的用法总结

    不同的版本的Swift中where用法有些不同,以最新的Swift4为准, if, guard, while三个语...

  • Swift where用法

    用法:fund xxxxx

  • Swift 模式匹配总结

    Swift 模式匹配总结 基本用法 对枚举的匹配: 在swift中 不需要使用break跳出当前匹配,默认只执行一...

  • swift 中的 where

    使用场景 switch 语句使用 where 配合 if let 限定某些条件。 配合 for 循环来添加限定条件...

  • Swift — 泛型(Generics)

    Swift — 泛型(Generics) [TOC] 本文将介绍泛型的一些用法、关联类型、where语句,以及对泛...

  • sql中where 的用法

    (1)where 后面有一个条件: SELECT * FROM LIST WHERE sendper="张三"; ...

  • Swift基础-02

    1.Swift中switch基本用法 关于 switch的特殊用法 2.Swift中区间 CountableRan...

  • Swift中的where使用

    1.首先where最常用的还是在协议部分(最主要还是给协议添加默认实现) 2.在使用泛型的时候也常常用到where...

  • Swift学习:闭包

    本篇将详细总结介绍Swift闭包的用法;闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift中的闭包与C...

  • 总结swift中模式匹配的用法

    看了一些介绍pattern matching的文章,里面有不少种使用用法。总结下来就是两种类型:绑定和判断。模式匹...

网友评论

    本文标题:Swift中where的用法总结

    本文链接:https://www.haomeiwen.com/subject/pajpmxtx.html