您能否在Swift 5的字符串.append()中编写forEach()闭包?到目前为止出现错误

问题描述 投票:-1回答:2

我是Swift的新手,我正在尝试用该语言进行实验,以使自己熟悉所有出色的功能。目前,我正在尝试编写forEach闭包以根据forEach中元素的值附加不同的字符串。变量lightStates[Bool]列表。我要寻找的是statusStr"1""0"的字符串,具体取决于b闭包中的forEach元素是true还是false,

我在闭包内的"Declared closure result 'String' is incompatible with contextual type 'Void'" ...行出现String in错误。

   var statusStr : String = ""
   statusStr.append(lightStates.forEach{ (b:Bool) -> String in return b ? "1":"0"})
   return "Lights: \(statusStr) \n"

理想情况下,我想知道我在做什么甚至是允许/可能。但我也乐于就如何获得所需的功能提出建议(基于"1"的数组打印"0"[Bool]的字符串)

foreach append closures swift5 swift-playground
2个回答
0
投票

是的,首先您做错了。 Foreach不返回任何内容,并且append函数需要添加一些内容。

您可以在这里使用map而不是foreach。像这样的东西

statusStr.append(contentsOf: array.map { $0.description == "true" ? "1" : "2" })

我知道这不是最佳解决方案,也不是最佳解决方案,但我只是想在这里清除逻辑。


0
投票

选项1(最简单):

lightStates.map { $0 ? "1" : "0" } .joined()

选项2(可重复使用

将位存储为整数类型(UInt最多可容纳64个,然后将其转换为字符串。

public extension Sequence {
  /// The first element of the sequence.
  /// - Note: `nil` if the sequence is empty.
  var first: Element? {
    var iterator = makeIterator()
    return iterator.next()
  }

  /// - Returns: `nil` If the sequence has no elements, instead of an "initial result".
  func reduce(
    _ getNextPartialResult: (Element, Element) throws -> Element
  ) rethrows -> Element? {
    guard let first = first
    else { return nil }

    return try dropFirst().reduce(first, getNextPartialResult)
  }

  /// Accumulates transformed elements.
  /// - Returns: `nil`  if the sequence has no elements.
  func reduce<Result>(
    _ transform: (Element) throws -> Result,
    _ getNextPartialResult: (Result, Result) throws -> Result
  ) rethrows -> Result? {
    try lazy.map(transform).reduce(getNextPartialResult)
  }
}
public extension BinaryInteger {
  /// Store a pattern of `1`s and `0`s.
  /// - Parameter bitPattern: `true` becomes `1`; `false` becomes `0`.
  /// - Returns: nil if bitPattern has no elements.
  init?<BitPattern: Sequence>(bitPattern: BitPattern)
  where BitPattern.Element == Bool {
    guard let integer: Self = (
      bitPattern.reduce( { $0 ? 1 : 0 } ) { $0 << 1 | $1 }
    ) else { return nil }

    self = integer
  }
}
if let lightStatesInteger = Int(bitPattern: lightStates) {
  _ = String(lightStatesInteger, radix: 0b10)
}
© www.soinside.com 2019 - 2024. All rights reserved.