gpt4 book ai didi

arrays - 令人困惑的错误 : Optionality of map's variable changes it from single object to array

转载 作者:行者123 更新时间:2023-11-30 12:36:06 24 4
gpt4 key购买 nike

我有:

private var wrappedObjects: [WrapperClass]?

var objects: [SomeClass]?
{
didSet
{
self.wrappedObjects = objects.map{ WrapperClass($0) }
}
}

这会导致以下错误:

`Cannot convert value of type '[SomeClass]' to expected argument type 'SomeClass'`

但是,当我将一行更改为:

var objects: [SomeClass] = []

错误消失了。

为什么objects的可选性使得map认为$0要么是单个SomeClass要么是一个数组[SomeClass] 分别?

最佳答案

这里的问题是有两个 map(_:) 函数。 One for sequences :

public protocol Sequence {
// ...

/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
func map<T>(_ transform: (Iterator.Element) throws -> T) rethrows -> [T]

// ...
}

one for optionals :

public enum Optional<Wrapped> : ExpressibleByNilLiteral {
// ...

/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
public func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?

// ...
}

因此,当您在 [SomeClass]? 上调用 map 时,将使用第二个 map 函数,其中转换函数参数将类型为 [SomeClass],因为 map 将为您解开它,并对其应用给定的转换。

但是,当您在 [SomeClass] 上调用 map 时,将使用第一个 map 函数,其中的元素将被迭代through——将变换函数应用到它们中的每一个上。因此,转换函数的参数类型将为 SomeClass

因此,一个有趣的解决方案是使用 map 两次 - 一次展开,一次对元素应用转换:

self.wrappedObjects = objects.map{ $0.map{ WrapperClass($0) } }

但是,这绝对是荒谬的,你绝对应该使用可选链接 as Rob suggests .

关于arrays - 令人困惑的错误 : Optionality of map's variable changes it from single object to array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com