将 [UInt8] 转换为另一个数组中结构的参数

Cast a [UInt8] to a parameter of a struct in another array

我希望我的函数设置 var“channel”的所有“选定”级别,类似于在“setLevel”函数中完成的方式。理想情况下,将其构建到我的 map/zip 函数中会很酷,因为函数首先是 class 公民。

public struct Channel {
    public var level: UInt8 = 0
    public var isEnabled: Bool = false
    public var isSelected: Bool = false

    public init() {}
}

public final class Universe {
    var channels = [Channel](repeating: Channel(), count: 512)

    public func setLevel(_ level: UInt8, forChannel index: Int){
        channels[index].level = level
    }

    public func setLevels(_ newVal: UInt8, forChannels selections: [Bool], array oldArray: [UInt8]) -> [Channel] {
        let newArray = zip(oldArray, selections).map {
            (oldVal, flag) in flag ? newVal : oldVal

        }
        return channels[index].level = newArray //here’s where I’m stuck
    }
}

您可以使用 channelsnewArray 进行另一个压缩:

public func setLevels(_ newVal: UInt8, forChannels selections: [Bool], array oldArray: [UInt8]) -> [Channel] {
    let newArray = zip(oldArray, selections).map {
        (oldVal, flag) in flag ? newVal : oldVal

    }
    return zip(channels, newArray).map { [=10=].0.withLevel([=10=].1) }
}

其中 withLevelChannel 中的方法:

public func withLevel(_ level: UInt8) -> Channel {
    var copy = self
    copy.level = level
    return copy
}