SwiftiOS DeveloperSwift开发技巧

把Swift弄得有点像Ruby

2016-02-19  本文已影响273人  子达如何

第一次接触Ruby看到这样的表达式的时候, 确实有点惊呆了

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..<self {
            action(i)
        }
    }
    public func times(action: ()->Void) {
        for _ in 0..<self {
            action()
        }
    }
}

extension Range {
    public func each(action: (Range.Generator.Element) -> Void) {
        for i in self {
            action(i)
        }
    }
}

不禁感概, 这个extension也太霸道了.
再结合一点儿自定义运算符, 运算符重载什么的, 以后用Swift写的东西可不是每个懂Swift语言的人都能看得懂了:)


抛个砖先放这里, 等吃透了可变参数以及Tuple之后, 再回头看看这块砖~

或许我们可以用Python的%格式化字符串的方式来格式化Swift的字符串哦~

public func %<T: CVarArgType>(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味道.

上一篇 下一篇

猜你喜欢

热点阅读