我想将闭包存储在数组中。但我不知道该怎么做,否则我的想法是完全错误的。使用下面所示的设置,我得到了一个错误:
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))
}
}发布于 2018-10-11 11:23:23
将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/stupidStorieshttps://stackoverflow.com/questions/52757523
复制相似问题