Swift脚本

看博客突然看到swift也可以写脚本了,简单研究了一下
运行脚本命令:swift swiftscript.swift(脚本文件名称)

#!/usr/bin/env swift
import Foundation

let filePath = "/Users/orrhsiao/Desktop/script"
let oldName = "/Users/orrhsiao/Desktop/script/a.aa"
let newName = "/Users/orrhsiao/Desktop/script/b.bb"

/// 获取文件夹的所有内容
/// - Parameter atPath: <#atPath description#>
/// - Returns: <#description#>
func getContensOfDir(atPath path: String) -> [String] {
    let fm = FileManager.default
    do {
        let contents = try fm.contentsOfDirectory(atPath: filePath)
        return contents
    }catch let error {
        print(error)
        let arr: Array<String> = []
        return arr
    }
}

/// 修改文件名称
/// - Parameters:
///   - newName: <#newName description#>
///   - oldName: <#oldName description#>
/// - Returns: <#description#>
@discardableResult func changeFileName(oldPath: String, newPath: String) -> Bool {
    let fm = FileManager.default
    let isExist = fm.fileExists(atPath: oldName)
    if isExist == false {
        print("目标路径文件不存在")
        return false
    }
    var state = false
    do {
        try fm.moveItem(at: URL(fileURLWithPath: oldName), to: URL(fileURLWithPath: newName))
        state = true
    }catch let error {
        print(error)
        state = false
    }
    return state
}


//changeFileName(oldPath: oldName, newPath: newName)
let cwd = FileManager.default.currentDirectoryPath
print("脚本运行于:\n" + cwd)

let content = getContensOfDir(atPath: filePath)
print("当前文件夹内容:\(content)")

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

推荐阅读更多精彩内容

  • swift脚本无论是.sh 格式,还是.swift格式,都需要以#!/usr/bin/env swift开头,来指...
    枫林风雨阅读 4,287评论 1 6
  • 自从Xcode8之后就不支持插件了,没法用Xcode一键生成AppIcon,一直没找到好的解决方案,一怒之下决定自...
    W_C__L阅读 1,970评论 4 11
  • 1.需求更改xcode build id PlistBuddy 为操作plist文件的命令行工具swift 通过p...
    7ee04efc3085阅读 488评论 0 2
  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 8,184评论 1 19
  • Linux命令行与脚本编程大全:https://pan.baidu.com/s/1WaIdrL4H8UmVBDdq...
    Danielyep阅读 642评论 0 0