swift编写命令行工具

前端之家收集整理的这篇文章主要介绍了swift编写命令行工具前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。



原文:
https://www.raywenderlich.com/128039/command-line-programs-os-x-tutorial

练习写的代码:

https://github.com/uniquejava/Panagram

知识点:

取程序名
let executableName = (Process.arguments[0] as NSString).lastPathComponent

取命令行参数个数
let argCount = Process.argc

取参数数组(比如第一个参数)
let argument = Process.arguments[1]

字符串操作
截取
argument.substringFromIndex(argument.startIndex.advancedBy(1)))

替换:
self.lowercaseString.stringByReplacingOccurrencesOfString(" ",withString: "")

反转:
String(str.characters.reverse())

排序:
str.characters.sort()

去掉换行符
str = NSString(data: inputData,encoding: NSUTF8StringEncoding)!
str.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())

扩展
命名StringExtension.swift
语法extension String{ func methodA() {}}

比较==
比较字符串相等,
"hello" == "hello"
比较数组相等
["hello","world"] == ["hello","world"]

标准输入STDIN

func getInput() -> String {
    
     // 使用OC的API
     //1
     let keyboard = NSFileHandle.fileHandleWithStandardInput()
     
     //2
     let inputData = keyboard.availableData
     
     //3
     let strData = NSString(data: inputData,encoding: NSUTF8StringEncoding)!
     
     //4
     return strData.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
    
    // 或者使用swift中新的API
    //return readLine()!
    
}


标准及错误输出STDOUT,STDERR

func writeMessage(message: String,to: OutputType = .Standard) {
    switch to {
    case .Standard:
        print("\u{001B}[;m\(message)")
    case .Error:
        fputs("\u{001B}[0;31m\(message)\n",stderr)
    }
}

定义enum

enum OutputType {
    case Error
    case Standard
}

enum OptionType: String {
    case Palindrome = "p"
    case Anagram = "a"
    case Help = "h"
    case Quit = "q"
    case Unknown
    
    init(value: String) {
        switch value {
        case "a":
            self = .Anagram
        case "p":
            self = .Palindrome
        case "h":
            self = .Help
        case "q":
            self = .Quit
        default:
            self = .Unknown
        }
    }
}
原文链接:https://www.f2er.com/swift/323631.html

猜你在找的Swift相关文章