把Swift弄得有点像Ruby

第一次接触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味道.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于 Swift 重要这个文档所包含的准备信息, 是关于开发的 API 和技术的。这个信息可能会改变, 根据这个文...
    无沣阅读 4,392评论 1 27
  • Swift学习有问必答群 : 313838956 ( mac版QQ有权限要求, 入群只能通过手机版 QQ申请...
    Guards翻译组阅读 6,669评论 9 13
  • 一直没有时间好好看一下swift,最近复习了一遍语法,这里记录swift学习过程中遇到的一些问题和要点,和Obje...
    bomo阅读 2,438评论 0 25
  • 一、python 变量和数据类型 1.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序...
    绩重KF阅读 1,791评论 0 1
  • 坚持每一天都写吧,自己
    风在睡觉阅读 149评论 0 0