swift - 快速实现泛型方法

标签 swift generics struct associated-types protocol-oriented

我正在 Swift 中实现面向协议(protocol)的方法,代码如下。这个概念看起来很有趣,但我希望你能理解。我的问题是如何为重复的打印任务实现通用功能。预先感谢您。

protocol Food {
    var name: String { get }
}

struct Grass: Food {
    var name: String { return "Grass" }
    var calcium: Float!
}

struct Rice: Food {
    var name: String { return "Rice" }
    var calories: Float!
}

struct Insect: Food {
    var name: String { return "Insect" }
    var fiber: Float!
}

protocol Eat {
    associatedtype food: Food
    var name: String { get }
    var itsFood: food { get }
}

struct Cow: Eat {
    typealias food = Grass
    var name: String { return "Cow" }
    var itsFood: food {return food(calcium: 100)}
}

struct People: Eat {
    typealias food = Rice
    var name: String { return "People" }
    var itsFood: food {return food(calories: 1000)}
}

struct Reptile: Eat {
    typealias food = Insect
    var name: String { return "Reptile" }
    var itsFood: food {return food(fiber: 300)}
}

let cow = Cow()
print(cow.name)
print(cow.itsFood.name)
print(cow.itsFood.calcium)

let people = People()
print(people.name)
print(people.itsFood.name)
print(people.itsFood.calories)

let reptile = Reptile()
print(reptile.name)
print(reptile.itsFood.name)
print(reptile.itsFood.fiber)

最佳答案

如果我没理解错的话,您需要一种方法来编写一个函数来打印出Eat conformer 的名称、食物名称和食物的营养值(value)。

您当前的食物 协议(protocol)未获得有关食物营养值(value)(钙、卡路里、纤维)的足够信息。你应该编辑你的协议(protocol):

protocol Food {
    var name: String { get }
    var nutritionalValueName: String { get }
    var nutritionalValue: Float! { get }
}

并在 Food conformers 中实现 2 个新属性。这是一个例子:

struct Grass: Food {
    var name: String { return "Grass" }
    var calcium: Float!

    var nutritionalValue: Float! { return calcium }
    var nutritionalValueName: String { return "Calcium" }
}

现在,您可以编写函数了。注意,由于Eat有关联类型,不能直接作为参数类型,需要引入泛型参数T,约束为Eat:

func printEat<T: Eat>(eat: T) {
    print(eat.name)
    print(eat.itsFood.name)
    print("\(eat.itsFood.nutritionalValueName): \(eat.itsFood.nutritionalValue!)")
}

函数体是不言自明的。

你可以这样调用它:

printEat(eat: Cow())
printEat(eat: People())
printEat(eat: Reptile())

输出:

Cow
Grass
Calcium: 100.0
People
Rice
Calories: 1000.0
Reptile
Insect
Fiber: 300.0

关于swift - 快速实现泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013863/

相关文章:

swift - 如何在 swift 3 中的图像上的两点之间画一条线?

swift - 在 Swift 闭包中解压嵌套元组

java - 无法使用不同类型的参数实现接口(interface)

java - 如何在没有未经检查的分配的情况下从通用接口(interface)检索对象列表?

c++ - C/C++ 结构与类

c - 如何使这个结构体实例在 C 中可变?

Swift 闭包作为元组中的字段

swift - 在 UICollectionView 中的小单元格上使用左插图进行分页

c# - 枚举类型的通用签名

C代码,搜索功能