美文网首页
Swift: typealias、associatedtype

Swift: typealias、associatedtype

作者: yehkong | 来源:发表于2017-05-27 16:27 被阅读0次

    typealias的用法:

    typealias是给现有的类型(包括系统和自定义的)进行重新命名,然后就可以用该别名来代替原来的类型,已达到改善程序可读性,而且可以自实际编程中根据业务来重新命名,可以表达实际意义。

    使用方法:typealias <#type name#> = <#type expression#>
    用法实例:typealias DistanceUnit = Float //表示距离
    

    有一个细节要注意就是:在涉及泛型重名时,不能将整个泛型类型进行重命名,还是看实例:

    struct Dog<T> {}
    typealias collie = Dog
    typealias collie1<T> = Dog<T>
    typealias wolfDog = Int
    typealias collie2 = Dog<wolfDog>
    
    typealias collie3= Dog<T> //Use of undeclared type 'T'不能通过编译
    
    • 我个人是这么理解:定义的新名字新类型必须满足确定性;上面的typealias collie3= Dog<T>中T不确定,所以不能合并定义到左值中。

    associatedtype的用法:

    在定义协议时,可以用associatedtype声明一个或多个类型作为协议定义的一部分,叫关联类型。这种关联类型为协议中的某个类型提供了别自定义名字,其代表的实际类型或实际意义在协议被实现时才会被指定。用法实例如下:

    protocol printObj {
        associatedtype ObjType //声明关联类型
        func printObj(_ obj:ObjType)
    }
    
    class printClass :printObj {
        typealias ObjType = String //指定实际类型
        func printObj(_ obj: printClass.ObjType) {
            print("obj:\(obj)")
        }
    }
    
    • 上面的代码再扩展就可以在不同的类中通过typealias指定不同的打印类型,实现不同的打印方法

    相关文章

      网友评论

          本文标题:Swift: typealias、associatedtype

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