Swift Playground流程

以下通过终端swiftc命令生成执行文件,成功编译进程 .
Xcode游乐场如何处理?

Rand.swift

public struct RandGenerator {
    private var rid: UInt
    init(seed:Int) { rnd = UInt(seed) }
    mutating func random() -> Int {
        rnd = (rnd & 10777) &+ 13577
        return Int(rnd & 0xffff)
    }
    mutating func xrand() -> Int {
        let n = random() & 0x07
        return random() >> n
    }
}

Analyzer.swift

func analyzer(_ t: Int) -> [(String, Int)] {
    let elems = ["努力", "怠惰", "幸運", "打算", "誤", "根性", "徹夜", "信念", "博愛", "疲労", "勤勉", "不安"]
    var rnd = RandGenerator(seed: t) // 乱数の初期化
    var score = [Int]()
    for _ in 0 ..< elems.count { score.append(rnd.xrand()) }
        let tops = zip(elems, score).sorted{ $0.1 > $1.1 }.prefix(5)
        let total = Double(tops.reduce(0){ $0 + $1.1 })
        return tops.map{ ($0.0, Int(Double($0.1 * 100) / total + 0.5)) }
}

Main.swift

print("あなたの名前: ", terminator:"")
if let name = readLine() {
    let v = Int(name.utf16.reduce(UInt16(0), &+))
    print("\(name)さんのプログラムは、")
    for (elm, val) in analyzer(v) {
        print(" \(elm):\(val)%", terminator:"")
    }
    print(" 出てきています。")
}

回答(1)

2 years ago

也许你想知道如何在Swift游乐场测试这个程序 .

readLine 功能在游乐场中不起作用 . 它只返回 nil .

你必须以其他方式获得 name . 最简单的方法就是用它来代替 readLine

print("あなたの名前: ", terminator:"")
let name = "tamiya"; do {
    let v = Int(name.utf16.reduce(UInt16(0), &+))
    print("\(name)さんのプログラムは、")
    for (elm, val) in analyzer(v) {
        print(" \(elm):\(val)%", terminator:"")
    }
    print(" 出てきています。")
}

输出:

あなたの名前: tamiyaさんのプログラムは、
 怠惰:20% 打算:20% 根性:20% 信念:20% 疲労:20% 出てきています。

翻译,根据Google

Your name: tamiya's program,
 Laziness: 20% Computation: 20% Gut: 20% Belief: 20% Fatigue: 20% has come out.