简体   繁体   English

Swift keyPath与协议

[英]Swift keyPath vs protocol

I understand the basic idea of keyPaths but I do not understand its use cases. 我了解keyPaths的基本概念,但不了解其用例。 If you already know the type of the instance, you can access their properties easily. 如果您已经知道实例的类型,则可以轻松访问其属性。 If you don't, protocol already supports read-only, read-write properties. 如果您不这样做,那么协议已经支持只读,读写属性。 Can someone explain me what I am missing? 有人可以向我解释我所缺少的吗? Anything that we can't do with protocols but keyPaths or when keypaths are better than protocols? 除了keyPath或keypath比协议更好时,我们无法使用协议做任何事情?

If you already know the type of the instance, you can access their properties easily. 如果您已经知道实例的类型,则可以轻松访问其属性。 If you don't, protocol already supports read-only, read-write properties. 如果您不这样做,那么协议已经支持只读,读写属性。 Can someone explain me what I am missing? 有人可以向我解释我所缺少的吗?

What you're missing is a sense of what's unknown. 您所缺少的是一种未知的感觉。

In both your sentences you speak of knowing what the instance's properties are. 在这两个句子中,您都说知道实例的属性是什么。 That's not the problem key paths solve. 这不是关键路径解决的问题。 Key paths have nothing to do with knowing the type; 关键路径与知道类型无关。 they are not in any kind of opposition to types or protocols. 它们不反对类型或协议。 On the contrary, before you can use a key path, you have to know exactly what the instance's properties are. 相反,在使用键路径之前,您必须确切地知道实例的属性是什么。

Key paths are for when what is unknown is which property to access. 关键路径是什么时,未知是访问哪个属性。 They provide a way to pass a property reference so that someone else can be told to access that property. 它们提供了一种传递属性引用的方法,以便可以告知其他人访问属性。

For example, here's a Person type: 例如,这是一个Person类型:

struct Person {
    let firstName : String
    let lastName : String
}

And here is a function that sorts an array of Persons by either the firstName or the lastName , without knowing which one to sort by: 这里是通过排序一者的阵列的功能firstName lastName ,在不知道进行排序,其中一个条件:

func sortArrayOfPersons(_ arr:[Person], by prop: KeyPath<Person, String>) -> [Person] {
    return arr.sorted { $0[keyPath:prop] < $1[keyPath:prop] }
}

A key path is how you tell this function what property to use as a basis for sorting. 关键路径是如何告诉此函数将哪个属性用作排序的基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM