美文网首页
Swift 关键字(typealias、associatedTy

Swift 关键字(typealias、associatedTy

作者: sampson666888 | 来源:发表于2021-10-13 12:59 被阅读0次

typealias

使用typealias为常用数据类型起一个别名,一方面更容易通过别名理解该类型的用途,另一方面还可以减少日常开发的代码量。

// 网络请求常用回调闭包
typealias success = (_ data: String) -> Void
typealias fail = (_ error: String) -> Void

func fetchData(_ url: String, success: success, fail: fail) {
}

// 用&连接多个协议
typealias UITableViewCommonProtocol = UITableViewDelegate & UITableViewDataSource

class TestDelegate:UITableViewCommonProtocol{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        return cell
    }
}

associatedType

associatedtypen表示位置的数据类型,只是先定义一个名字,具体表示的类型要在最终使用的时候进行赋值。在定义协议时,可以用associatedtype声明一个或多个类型作为协议定义的一部分。

protocol NetworkRequest {
    associatedtype DataType
    func didReceiveData(_ data: DataType)
}

class ViewModel: NetworkRequest {
    
    typealias DataType = String
    
    func didReceiveData(_ data: DataType) {
        
    }
    
}

相关文章

  • Swift 关键字(typealias、associatedTy

    typealias 使用typealias为常用数据类型起一个别名,一方面更容易通过别名理解该类型的用途,另一方面...

  • Swift 5.0-typealias与associatedty

    Swift 中关键字typealias重命名与associatedtype关联对象,在实际开发中比较常见。 typ...

  • Swift基础

    变量 常量 除数为0的时候 在swift 中 typealias 关键字(取别名的) 数组

  • swift - typealias详解

    typealias 如果挑出swift中好用的功能,我认为typealias 应该是首当其冲的了typealias...

  • Swift - typealias

    typealias用来为已存在的类型重新定义名称的。 通过命名,可以使代码变得更加清晰。使用的语法也很简单,使用 ...

  • Swift 中类型别名的用途

    什么是 typealias? 当我们回忆那些 Swift 强大的语言特性时,很少有人会首先想到 typealias...

  • Swift: typealias、associatedtype

    typealias的用法: typealias是给现有的类型(包括系统和自定义的)进行重新命名,然后就可以用该别名...

  • Swift 2.1  typealias

    typealias是用来给已经存在的类型重新命名名字的,通过命名,我们可以写出更加清晰的代码。 typealias...

  • Swift typealias使用

    typealias 类型定义总结 给已有类型重新定义名称,方便代码阅读 定义闭包,类似oc的block 定义 闭包定义

  • Swift typealias 介绍

    typealias : 类型别名, alias 别名的意思

网友评论

      本文标题:Swift 关键字(typealias、associatedTy

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