我可以有一个没有函数的 Swift 协议吗 [英] Can I have a Swift protocol without functions

查看:42
本文介绍了我可以有一个没有函数的 Swift 协议吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个典型的例子,有时会在教程等中看到(即使在 Apple 的代码中):

Consider this typical example, sometimes seen in tutorials, etc (even in Apple's code):

protocol Nameable {
     var name: String {get}
}

struct Person : Nameable {
     var name: String
}

我的问题是,这种模式有什么好处?一旦将函数添加到协议中,我就可以理解了,但是对于只有一个或多个变量的协议来说,什么是好的应用程序呢?为什么不将 name 添加到每个 structclass ?

My question is, what would be the benefit of this pattern? I can understand it once a function is added to a protocol, but what could be a good application for a protocol with just one or more variables? Why not just add name to each struct and class ?

推荐答案

Person 不是您可能想要命名的唯一事物.宠物有名字,道路有名字,见鬼,有些人给他们的车取名.

Persons are not the only not the only things that you may want to name. Pets have names, roads have names, heck, some people name their cars.

如果我们想为不同对象集合中的每个对象命名怎么办?如果我们将这些对象存储在 Any 的集合中,我们就无法保证所有对象都有名称.

What if we want to name each object in a collection of different objects? If we store those objects in a collection of Any, we don't have any way to guarentee that all objects have names.

这就是协议的用武之地.通过创建Nameable 协议,我们可以创建Nameable 对象的集合,并确保其中的所有对象都保证有个名字.

This is where protocols come in. By creating a Nameable protocol, we can create a collection of Nameable objects, and be certain that all the objects within are guaranteed to have a name.

这是一个例子:

protocol Nameable {
    var name: String {get}
}

struct Person : Nameable {
    let name: String
    let age: Int
    // other properties of a Person
}

struct Pet : Nameable {
    let name: String
    let species: String
    // other properties of a Pet
}

struct Car : Nameable {
    let name: String
    let horsepower: Double
    // other properties of a Car
}

let namableItems: [Nameable] = [
    Person(name: "Steve", age: 21),
    Pet(name: "Mittens", species: "Cat"),
    Car(name: "My Pride and Joy", horsepower: 9000)
]

for nameableItem in namableItems {
    print("\(nameableItem.name) is a \(nameableItem.dynamicType).")
}

打印:

史蒂夫是一个人.

手套是宠物.

我的骄傲和喜悦是一辆汽车.

My Pride and Joy is a Car.

你可以在这里试试.

这篇关于我可以有一个没有函数的 Swift 协议吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆