美文网首页
Swift脚本

Swift脚本

作者: OrrHsiao | 来源:发表于2023-07-19 18:03 被阅读0次

    看博客突然看到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脚本

          本文链接:https://www.haomeiwen.com/subject/aacaudtx.html