🐶PlaygroundConsole

讓 print() 可以在 Swift Playgrounds 中方便使用。

import Combine
import PlaygroundSupport

// 🐶 PlaygroundConsole
public class PlaygroundConsole : 
    TextOutputStream, 
    CustomStringConvertible, 
    CustomPlaygroundDisplayConvertible 
{
    // console text
    private var text = ""
    
    // 🅿️ TextOutputStream
    public func write(_ string: String) { text += string }
    // 🅿️ CustomPlaygroundDisplayConvertible
    public var playgroundDescription: Any { text }
    // 🅿️ CustomStringConvertible
    public var description : String { text }
    
    // 1. static let (can't change this static instance)
    public static let `default` = PlaygroundConsole()
    
    // 2. public init (can create new instance)
    public init() {}
    
    // 3. other public services
    public func clear() { text = "" }
}

// 🌀 PlaygroundPage.console
extension PlaygroundPage {
    public static let console = PlaygroundConsole.default
}

/// shadows `Swift.print()`, prints to `PlaygroundConsole.shared`.
/// (based on [StackOverflow](https://stackoverflow.com/a/47223166))
public func print(
    _    items: Any..., 
    separator : String = " ", 
    terminator: String = "\n"
) {
    let output = items.map { "\($0)" }.joined(separator: separator)
    PlaygroundConsole.default.write(output + terminator)
}

Last updated