Вариант 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)
}