简体   繁体   中英

Protocols in Swift

I want to create a FileManager using protocols in Swift.

It is simply a struct

struct AppFile: AppFileManipulation {

    let fileName: String

    init(fileName: String)
    {
        self.fileName = fileName
    }

}

which is created in the code

let file = AppFile(fileName: "testfile.txt")

now I want to separate out different functions into different protocols

One of these gives the status for the file, here it is with file exists

protocol AppFileStatus
{
    func exists(file at: URL) -> Bool
}

extension AppFileStatus
{
    func exists(file at: URL) -> Bool
    {
        return FileManager.default.fileExists(atPath: at.path)
    }
}

and I want to have a separate protocol that has file operations

protocol AppFileManipulation : AppDirectoryNames, AppFileStatus
{
    func writeStringsToFile(containing: String, to path: FileManager.SearchPathDirectory, withName name: String) -> Bool
}

extension AppFileManipulation
{
        func writeStringsToFile(containing: String, to path: FileManager.SearchPathDirectory, withName name: String) -> Bool{

}
    }

Now for various reasons (to check if the file already exists, actually) I want the body of writeStringsToFile to access exists(file at: URL).

One solution would be to put everything into the same protocol, but really I wanted to split the functionality out. Another option would be to repeat code.

How should I structure this so I can access the AppFileStatus methods from within the AppFileManipulation protocol?

Here is a sample project; https://github.com/stevencurtis/ProtocolFileHandling

You might be looking for the where Self option for your extension:

struct AppFile: AppFileStatus, AppFileManipulation {

    let fileName: String

    init(fileName: String)
    {
        self.fileName = fileName
    }
}


protocol AppFileStatus
{
    func exists(file at: URL) -> Bool
}


extension AppFileStatus
{
    func exists(file at: URL) -> Bool
    {
        return FileManager.default.fileExists(atPath: at.path)
    }
}


protocol AppFileManipulation
{
    func writeStringsToFile(containing: String, to path: FileManager.SearchPathDirectory, withName name: String) -> Bool
}


extension AppFileManipulation where Self: AppFileStatus
{
    func writeStringsToFile(containing: String, to path: FileManager.SearchPathDirectory, withName name: String) -> Bool{
            let exists = self.exists(file: URL(fileURLWithPath: ""))

            return true
    }
}

and now you can call:

let file = AppFile(fileName: "testfile.txt")
file.writeStringsToFile(containing: ..., to: ..., withName: ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM