首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >map( keyPath ),其中keyPath是变量

map( keyPath ),其中keyPath是变量
EN

Stack Overflow用户
提问于 2020-09-06 13:20:52
回答 1查看 1.1K关注 0票数 3
代码语言:javascript
复制
let arr = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
arr.map(\.0) // [1, 2, 3, 4, 5]

效果很好。但是下面的代码没有编译:

代码语言:javascript
复制
let keyPath = \(Int, Int).0
arr.map(keyPath)

无法将'WritableKeyPath<(Int,Int),Int>‘类型的值转换为预期的参数类型((Int,Int))引发-> T’。 无法推断泛型参数'T‘。

EN

回答 1

Stack Overflow用户

发布于 2020-09-06 15:24:12

进化论建议展示了如何使用操作符,但您也可以使用相同的[]()语法,不管它是否部分应用,因为下标和函数不需要参数。

代码语言:javascript
复制
let oneTo5 = 1...5
let keyPath = \(Int, Int).0
XCTAssert(
  zip(oneTo5, oneTo5).map(keyPath[]).elementsEqual(oneTo5)
)
代码语言:javascript
复制
let keyPath = \Double.isZero
XCTAssertFalse(keyPath[1.0]())
代码语言:javascript
复制
public extension KeyPath {
  /// Convert a `KeyPath` to a partially-applied get accessor.
  subscript() -> (Root) -> Value {
    { $0[keyPath: self] }
  }

  /// Convert a `KeyPath` to a get accessor.
  subscript(root: Root) -> () -> Value {
    { root[keyPath: self] }
  }
}

public extension ReferenceWritableKeyPath {
  /// Convert a `KeyPath` to a partially-applied get/set accessor pair.
  subscript() -> (Root) -> Computed<Value> {
    { self[$0] }
  }

  /// Convert a `KeyPath` to a get/set accessor pair.
  subscript(root: Root) -> Computed<Value> {
    .init(
      get: self[root],
      set: { root[keyPath: self] = $0 }
    )
  }
}
代码语言:javascript
复制
/// A workaround for limitations of Swift's computed properties.
///
/// Limitations of Swift's computed property accessors:
/// 1. They are not mutable.
/// 2. They cannot be referenced as closures.
@propertyWrapper public struct Computed<Value> {
  public typealias Get = () -> Value
  public typealias Set = (Value) -> Void

  public init(
    get: @escaping Get,
    set: @escaping Set
  ) {
    self.get = get
    self.set = set
  }

  public var get: Get
  public var set: Set

  public var wrappedValue: Value {
    get { get() }
    set { set(newValue) }
  }

  public var projectedValue: Self {
    get { self }
    set { self = newValue }
  }
}

//MARK:- public
public extension Computed {
  init(
    wrappedValue: Value,
    get: @escaping Get = {
      fatalError("`get` must be assigned before accessing `wrappedValue`.")
    },
    set: @escaping Set
  ) {
    self.init(get: get, set: set)
    self.wrappedValue = wrappedValue
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63764608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档