SwiftをRubyに似てる

2201 ワード

ルビーに初めて触れてこんな表現を見たときは、確かにちょっと驚きました
3.times { print "Hi!" }
1.upto(9) {|i| print i }
0.step(11,3) {|i| print i }
(1..9).each {|i| print i }

最近Swiftを習って見たとき、SwiftもRubyに似ていることに気づいた.まずSwiftにどう書くか見てみましょう
        0.upto(10) { print("upto\($0)") }
        10.downto(0) { print("downto") }
        10.times { print("Hello")}
        10.times { index in print("Hello\(index)") }
        
        (1...10).each { print("each\($0)") }

もちろん、直接このようなコードをつけたいなら、十中八九コンパイラは間違っています.しかし、次のような小さなコードを加えるだけで、状況はずっとよくなります.
import Foundation
extension Int {
    public func upto(to: Int, action: (Int)->Void) {
        for i in self...to {
            action(i)
        }
    }
    public func upto(to: Int, action: ()->Void) {
        for _ in self...to {
            action()
        }
    }
    public func downto(to: Int, action: (Int)->Void) {
        for i in to...self {
            action(i)
        }
    }
    public func downto(to: Int, action: ()->Void) {
        for _ in to...self {
            action()
        }
    }
    
    public func times(action: (Int)->Void) {
        for i in 0..Void) {
        for _ in 0.. Void) {
        for i in self {
            action(i)
        }
    }
}

思わず、このextensionはあまりにも横暴だと感じた.もう少しカスタム演算子、演算子のリロードなどを組み合わせて、後でSwiftで書くものはSwift言語を知っている人一人一人が理解できるものではありません:)
レンガを投げてここに置いて、可変パラメータとTupleを食べ終わったら、このレンガを振り返ってみましょう.
もしかするとPythonの%フォーマット文字列でSwiftの文字列をフォーマットできるかもしれませんよ~
public func %(format: String, args: T) -> String {
    return String(format: format, arguments: [args])
}

public func %(format: String, args: [CVarArgType]) -> String {
    return String(format: format, arguments: args)
}
        let s1 = "Python style %d" % 10;
        print("\(s1)")
        let s2 = "Python style %d %@" % [10, "monster"];
        print("\(s2)")

この使用形態にはまだ完全ではないPythonの味がある.