美文网首页swift
Swift 关键字 -- associatedtype

Swift 关键字 -- associatedtype

作者: 呵呵_7380 | 来源:发表于2022-05-31 10:22 被阅读0次

associatedtype

关联类型的关键字,处理 协议 中的范型使用场景

实现 Stack 协议

错误例子:

protocol Stack<Element> {

}

错误信息:Protocols do not allow generic parameters; use associated types instead

protocol 不支持范型,需要使用 associatedtype 来代替

正确使用:

protocol Stack {
    associatedtype Element
    
    func push(e: Element) -> Void
    
    func pop() -> Element
}

associatedtype 支持在 protocol 中实现范型的功能。

错误例子:

class StackCls {
    associatedtype E
}

错误信息: Associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement

正确使用:

class StackCls {
    typealias E
}

总结

associatedtype 只能在 protocol 中使用,class 中应该使用typealias进行代替。

使用 case

1. class 范型结合associatedtype
class Stack<T>: Stackble {
    typealias Element = T
    
    func push(e: T) {
        
    }
    
    func pop() -> T? {
        return nil
    }
}

/// 指定类型 Stack
let strStack = Stack<String>()
strStack.push(e: "")
let result = strStack.pop()

相关文章

网友评论

    本文标题:Swift 关键字 -- associatedtype

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