首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Swift数组中存储闭包

如何在Swift数组中存储闭包
EN

Stack Overflow用户
提问于 2018-10-11 10:12:59
回答 1查看 351关注 0票数 3

我想将闭包存储在数组中。但我不知道该怎么做,否则我的想法是完全错误的。使用下面所示的设置,我得到了一个错误:

代码语言:javascript
运行
复制
Cannot convert value of type '(Reader) -> (URL) -> ()' to expected element type '(URL) -> ()'

我不明白。我的班级:

代码语言:javascript
运行
复制
class Reader {
    let fileNamesActions:[( filename:String, action:(URL) -> () )]  = [
        (filename:"goodStories.txt", action: readGoodStories),
        (filename:"badStories.txt", action: readBadStories),
        (filename:"stupidStories", action: readStupidStories)]

我宣布了这样的职能:

代码语言:javascript
运行
复制
    func readGoodStories(from url:URL) {
        //read, do whatever i want with url
    }
    ...

我称他们为:

代码语言:javascript
运行
复制
    init (with url:URL) {    
         for (filename, action) in fileNamesActions {
             action(url.appendingPathComponent(filename))
         }
     }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-11 11:23:23

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

代码语言:javascript
运行
复制
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)
    }
}

使用

代码语言:javascript
运行
复制
let reader = Reader(with: URL(string: "www.xxxxxxxxxx.com")!)

输出

代码语言:javascript
运行
复制
www.xxxxxxxxxx.com/goodStories.txt
www.xxxxxxxxxx.com/badStories.txt
www.xxxxxxxxxx.com/stupidStories
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52757523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档