美文网首页
Swift中associatedtype

Swift中associatedtype

作者: xmb | 来源:发表于2021-01-26 14:10 被阅读0次
// associatedtype定义关联类型,相当于类型的占位符,让实现协议的类型来指定具体的类型

protocol Food {
    
}

protocol Animal {
    associatedtype F: Food
    func eat(_ food: F)
}

struct Meat: Food {
    
}

struct Grass: Food {
    
}

struct Tiger: Animal {
    func eat(_ food: Meat) {
        print("eat \(food)")
    }
}

struct Sheep: Animal {
    func eat(_ food: Grass) {
        print("eat \(food)")
    }
}

func test() {
    let tiger = Tiger()
    tiger.eat(Meat())

    let sheep = Sheep()
    sheep.eat(Grass())
}

/*

Protocol 'Animal' can only be used as a generic constraint because it has Self or associated type requirements
只能被用作泛型约束,不能当做独立的类型使用
 
错误代码:
func isTiger(animal: Animal) -> Bool {

}
*/

// 具有关联类型的协议类型,只能当做泛型约束使用
func isTiger<A: Animal>(animal: A) -> Bool {
    if animal is Tiger {
        return true
    } else {
        return false
    }
}

相关文章

  • Swift中associatedtype

  • Swift associatedtype

    在协议中除了定义属性和方法外,我们还能定义类型的占位符,让实现协议的类型来指定具体的类型。 添加 associat...

  • swift关键字全集

    >>>Swift中所有关键字分类: 用在声明中的关键字: associatedtype 、 class 、 dei...

  • Swift 5.0-typealias与associatedty

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

  • 2018-03-08

    Swift关键字 associatedtype: 协议-关联类型, 作用:为协议中的某个类型提供了一个占位名(或者...

  • Swift: typealias、associatedtype

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

  • swift - associatedtype的妙用

    开发中你经常能遇到这样的业务场景.许多列表视图表格数据格式差不多.你会设计很多的协议里面包含各种数据源的类型(取名...

  • swift associatedtype和typealias

    typealias 1、可以用来对已有的类型进行重命名,比如在表示两点之间的距离的时候,可以使用typealias...

  • swift3.0:associatedtype

    E文:https://developer.apple.com/library/content/documentat...

  • swift的protocol带有associatedtype

    当protocol中带有associatedtype或者Self约束时,这个协议就不能被当作一个独立的类型使用了,...

网友评论

      本文标题:Swift中associatedtype

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