zoukankan      html  css  js  c++  java
  • Swift开发第三篇——Playground

    本篇分为两部分:

    一、Playground的延时运行

    二、Playground的可视化


    一、Playground的延时运行

      Playground 就是提供一个可以即时编译的类似 REPL 的环境,他为我们提供了一个顺序执行的环境,在每次更改其中代码后整个文件都会被重新编译,并清空原来的状态并运行。

    NSTimer 在默认的 Playground 中是不会执行的:  

    class TestClass {
        @objc func callMe() {
            print("Hi")
        }
    }
    let object = TestClass()
    NSTimer.scheduledTimerWithTimeInterval(1, target: object,
        selector: "callMe", userInfo: nil, repeats: true)

      在执行玩 NSTimer 语句之后,整个 Playground 将停止掉,Hi 永远不会被打印出来。Playground 执行完了所有语句,然后正常退出了。为了使 Playground 具有延时运行的本领,我们需要引入 Playground 的扩展包“XCPlayground” 框架,其中包含了能使 Playground 延时执行的黑魔法:XCPSetExecutionShouldContinueIndefinitely,只需在刚刚的代码上面加上:

    import XCPlayground  XCPSetExecutionShouldContinueIndefinitely(true)

    二、Playground的可视化

     在 Playground 中进行可视化演示只需使用XCPlayground框架的XCPCaptureValue方法来实现,在屏幕上呈现每一步算法的步骤。

    import XCPlayground
    var arr = [14, 11, 20, 1, 3, 9, 4, 15, 6, 19,
        2, 8, 7, 17, 12, 5, 10, 13, 18, 16]
    func plot<T>(title: String, array: [T]) {
        for value in array {
            XCPCaptureValue(title, value: value)
        }
    }
    plot("起始", array: arr)
    func swap(inout x: Int, inout y: Int) {
        (x, y) = (y, x)
    }
    func bubbleSort<T: Comparable>(inout input: [T]) {
        for var i = input.count; i > 1; i-- {
            var didSwap = false
            for var j = 0; j < i - 1; j++ {
                if input[j] > input[j + 1] {
                    didSwap = true
                    swap(&input[j], &input[j + 1])
                }
            }
            if !didSwap {
                break
            }
            plot("第 (input.count - (i - 1)) 次迭代", array: input)
        }
        plot("结果", array: input)
    }
    bubbleSort(&arr)
  • 相关阅读:
    四则运算结对作业
    读《构建之法》第四、十七章有感
    四则运算练习的命令行软件
    Spring01
    oop01
    运行shell脚本的三种方式
    正则表达式的基础组成部分
    C语言文件函数
    shell文件描述符及重定向
    shell基础
  • 原文地址:https://www.cnblogs.com/Jepson1218/p/5281055.html
Copyright © 2011-2022 走看看