使用swift的函数式来简化代码

2016-11-02  本文已影响33人  奈文摩尔定律

app中的附件下载存储及管理,我需要按照我自己的规则来寻找下载目录及相关属性组成的地址,如下是在制定地址中获取我所需的元组数据[UserAttach]以便我管理

1.获取路径

class func getAttachPath(userpath:Bool = false)->String{
        let model = getUserModel()
        var documents:String?
        let sp = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        if sp.count > 0 {
            documents = (userpath ? "\(sp[0])/ylzc/attach/\(model.0.phoneNumber!)/" : "\(sp[0])/ylzc/attach/")
        }
        let fileManager = NSFileManager.defaultManager()
        var isdir:ObjCBool = true
        if !fileManager.fileExistsAtPath(documents!, isDirectory: &isdir){
            do{
                try fileManager.createDirectoryAtPath(documents!, withIntermediateDirectories: true, attributes: nil)
            }catch let error as NSError {
                print("\(error.localizedDescription)")
            }
        }
        return documents!
    }

2.数据处理

typealias Attach = (path:String,fileName:String)
typealias UserAttach = (phoneNumber:String,attachs:[Attach],isExpland:Bool)
class ManageAttachmentVC: StructVC {
    var tableview:UITableView!
    let attachIdentifier = "attachIdentifier"
    
    lazy var nsfilemanager = NSFileManager.defaultManager()
    lazy var attachData:[UserAttach] = {
        //let nsfilemanager = NSFileManager.defaultManager()
        let path =  User_Model.getAttachPath()
        let pathdataDirectory:[String] = try! self.nsfilemanager.contentsOfDirectoryAtPath(path)
        print(pathdataDirectory)

        let data:[UserAttach] = pathdataDirectory.map{(directory:String)->UserAttach in
            let attachs = try! self.nsfilemanager.contentsOfDirectoryAtPath(path  + directory).map{(file:String)->Attach in
                return    (path:path  + directory + "/" + file, fileName:file)
            }
            return (directory,attachs,false)
        }
        //let count = data.reduce(0, combine:  {$0+$1.attachs.count})
        //return (data,count)
        return data
    }()
}
extension ManageAttachmentVC{

3.效果图

swift.png
上一篇 下一篇

猜你喜欢

热点阅读