ios - Swift 5.7 中的 any 和 some (译) - 技术分享-持续学习 - SegmentFault 思否
segmentfault.com · 279 words · saved by 1 readers
由于 any 和 some 都适用于协议,因此我想在这篇博文中将它们放在一起比较以便更好地解释它们解决分别解决了什么问题,以及在什么情况下使用 any、some 或其...
由于 any 和 some 都适用于协议,因此我想在这篇博文中将它们放在一起比较以便更好地解释它们解决分别解决了什么问题,以及在什么情况下使用 any、some 或其他的。 了解 any 和 some 解决的问题 为了解释 any 解决的问题,我们可以通过一个列子来了解这两个关键字。下面是一个Pizza模型的协议: protocol Pizza { var size: Int { get } var name: String { get } } 在Swift 5.6,你可能会写下面的这种方法,来接收一个Pizza func receivePizza(_ pizza: Pizza) { print("Omnomnom, that's a nice \(pizza.name)") } 当这个函数被调用时,receivePizza 函数接收一个所谓的披萨协议类型,我们可以理解为一个披萨盒子。为了知道这个披萨名称,必须打开这个盒子,也就是获取实现Pizza协议的具体对象,然后获取名称。这意味着 Pizza 几乎没有编译时优化,这使得 receivePizza 方法调用的开销比我们想要的更大。 另外下面的函数,看起来好像是一样的 func receivePizza<T: Pizza>(_ pizza: T) { print("Omnomnom, that's a nice…
saved by
related reading
- Swift Protocol 背后的故事(Swift 5.6/5.7) | 雪峰的blogzxfcumtcs.github.io
- Swift: From Protocol to AssociatedType then Type Erasure | Welcome to Monstarlab’s Engineering Blogengineering.monstar-lab.com
- Structs, Classes, and Actors in iOS Interviewsholyswift.app
- Craftrauno.me
- A half-hour to learn Rustfasterthanli.me
- Anytype — A safe haven for digital collaborationanytype.io
- Getting started with associated types in Swift Protocols - SwiftLeeavanderlee.com
- Documentationdocs.swift.org
- AnyView | Apple Developer Documentationdeveloper.apple.com
- Combine | Apple Developer Documentationdeveloper.apple.com
- Documentationdocs.swift.org
- Documentationdocs.swift.org