【问题标题】:What is the use of #keyPath rather than directly passing key as a String?#keyPath 而不是直接将键作为字符串传递有什么用?
【发布时间】:2019-05-14 19:12:34
【问题描述】:

这两种格式的有用区别是什么:

request.sortDescriptors = [NSSortDescriptor(key:"dateCreated", ascending: false)]

request.sortDescriptors = [NSSortDescriptor(key: #keyPath(Note.dateCreated), ascending: false)]

在第二种格式中,#keyPath 让我感到困惑。它到底是什么,我可以在哪里阅读更多相关信息?

【问题讨论】:

  • #keyPath 语法的巨大优势在于编译器会在编译时验证密钥路径,如果无效则抛出错误。
  • @vadian 感谢您的澄清。但是我们称之为#keyPath?我可以在哪里阅读更多这样的内容?
  • 提案SE 0062中有描述。

标签: swift directive kvc


【解决方案1】:

没有区别

key:"dateCreated"

key: #keyPath(Note.dateCreated)

两者都将使用 Note 对象的 dateCreated 属性进行排序 后者具有避免硬编码问题的优势,例如编写 datCreated 而不是 dateCreated 会引发编译时错误,因此它可以安全地避免在相同情况下前者肯定会发生的运行时崩溃

https://www.klundberg.com/blog/swift-4-keypaths-and-you/

http://chris.eidhof.nl/post/sort-descriptors-in-swift/

【讨论】:

  • #keyPath(Note.dateCreated) 将自动完成,key:"dateCreated" 不会,我认为这是唯一的区别。在功能上它们是相同的。
  • 是的,即使写错了编译器也会报错,这就是我所说的硬编码
  • 谢谢!但是我们称之为#keyPath?我可以在哪里阅读更多这样的内容?
猜你喜欢
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 2019-12-11
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多