如何在Swift数组中存储闭包

时间:2018-10-11 10:13:00

标签: swift

我想将闭包存储在数组中。但是我不知道该怎么做,否则我的想法是完全错误的。安装如下所示时,出现错误:

Cannot convert value of type '(Reader) -> (URL) -> ()' to expected element type '(URL) -> ()'

我不明白。我的课:

class Reader {
    let fileNamesActions:[( filename:String, action:(URL) -> () )]  = [
        (filename:"goodStories.txt", action: readGoodStories),
        (filename:"badStories.txt", action: readBadStories),
        (filename:"stupidStories", action: readStupidStories)]

我已经声明了这样的函数:

    func readGoodStories(from url:URL) {
        //read, do whatever i want with url
    }
    ...

我用以下方式称呼他们:

    init (with url:URL) {    
         for (filename, action) in fileNamesActions {
             action(url.appendingPathComponent(filename))
         }
     }

1 个答案:

答案 0 :(得分:3)

fileNamesActions的声明更改为lazy var,因为您正在访问其分配中的class成员,

class Reader {

    lazy var fileNamesActions:[( filename:String, action:(URL) -> () )]  = [
        (filename:"goodStories.txt", action: readGoodStories),
        (filename:"badStories.txt", action: readBadStories),
        (filename:"stupidStories", action: readStupidStories)]

    init (with url:URL) {
        for (filename, action) in fileNamesActions {
            action(url.appendingPathComponent(filename))
        }
    }

    func readBadStories(from url:URL) {
        print(url.path)
    }

    func readStupidStories(from url:URL) {
        print(url.path)
    }

    func readGoodStories(from url:URL) {
        print(url.path)
    }
}

用法

let reader = Reader(with: URL(string: "www.xxxxxxxxxx.com")!)

输出

www.xxxxxxxxxx.com/goodStories.txt
www.xxxxxxxxxx.com/badStories.txt
www.xxxxxxxxxx.com/stupidStories