2016年7月30日 星期六

swift script

沒想到swift也可以替代shell script

#!/usr/bin/swift -F Carthage/Build/Mac/
#只要開頭像這樣宣告就可以用swift xxx.swift執行
#另外 -F 是第三方framework的路徑

#!/usr/bin/env xcrun --toolchain "com.apple.dt.toolchain.Swift_2_3" --sdk machos swift
#使用特殊版本的swift

#請愛用carthage
#mkdir swift_btc_script
#cd swift_btc_script
#echo 'github "nomothetis/OptionKit" ~> 1.0' > Cartfile
#carthage update

2016年7月1日 星期五

swift強化版的enum

enum 水果 {
    case 櫻桃(價位: Int, 產地: String)
    case 火龍果(價位: Int, 產地: String)
    
    static let 價目表 = [
        櫻桃(價位: 3400, 產地: "華盛頓"),
        火龍果(價位: 1100, 產地: "埔里")
    ]
    
    private func valueAt(pos: Int) -> AnyObject? {
        if let first = Mirror(reflecting: self).children.first {
            let children = Mirror(reflecting: first.value).children
            let index = children.startIndex.advancedBy(IntMax(pos))
            if let value = children[index].value as? AnyObject {
                return value
            }
        }
        return nil
    }
    
    func 價位() -> Int {
        if let value = valueAt(0) as? Int {
            return value
        }
        
        return 0
    }
    
    private func valueAt(pos: Int, with: String) -> AnyObject? {
        if let first = Mirror(reflecting: self).children.first {
            if first.label == with {
                let children = Mirror(reflecting: first.value).children
                
                let index = children.startIndex.advancedBy(IntMax(pos))
                if let value = children[index].value as? AnyObject {
                    return value
                }
            }
        }
        return nil
    }
    
    static func 詢價(水果名: String) -> Int {
        for 價目 in 價目表 {
            if let price = 價目.valueAt(0, with: 水果名) as? Int {
                return price
            }
        }
        
        return 0
    }
}

水果.詢價("火龍果")