加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中where关键字的应用场景和用法

发布时间:2020-12-14 06:04:27 所属栏目:百科 来源:网络整理
导读:Swift中where关键字的应用场景和用法 //: [Previous](@previous)import Foundationimport UIKitvar str = "Hello,playground"//: [Next](@next)//笔记记录swift中where关键字的适用场景和方法//1.用在do...catch...中enum ExceptionError:Error{ case httpCo

Swift中where关键字的应用场景和用法

//: [Previous](@previous)

import Foundation
import UIKit

var str = "Hello,playground"

//: [Next](@next)
//笔记记录swift中where关键字的适用场景和方法



//1.用在do...catch...中
enum ExceptionError:Error{
    case httpCode(Int)
}

do {
    throw ExceptionError.httpCode(500)
}
catch ExceptionError.httpCode(let code) where code > 500 {
    print("server error")
}


//2.switch语句中
var value:(Int,String) = (1,"小明")
switch value {
case let (x,y) where x < 60:
    print("不及格")
default:
    print("及格")
}



//3.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)
}



//4.与泛型结合
func genericity1<S>(s: S) where S: Equatable {
    
}
//另一种写法
func genericity2<S: Equatable>(s: S) {
    
}




//5.与协议结合
protocol aProtocol{}
extension aProtocol where Self:UIView{
    //只给遵守myProtocol协议的UIView添加了拓展
    //强大的协议拓展  可以给协议添加默认实现   面向协议编程的基础
    func getString() -> String{
        return "string"
    }
    
}
class MyView:UIView{}
extension MyView:aProtocol{}
let myView = MyView()
let aStr = myView.getString()

//给数组中元素遵守Equatable协议的数组添加扩展
public extension Array where Array.Element : Equatable  {
    
    /// 移除数组中的一个指定元素
    ///
    /// - Parameter obj: 指定的元素
    public mutating func removeObject(_ obj: Array.Element) {
        
        guard let idx = self.index(of: obj) else {
            return
        }
        remove(at: idx)
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读