创建元组数组来调用函数但无法获得返回

时间:2017-01-22 14:02:35

标签: ios arrays swift function tuples

我创建了一些返回类型为Void的函数 - > UIImage和我已经建立了一个类" FilterApplier"按顺序调用功能。这个想法是每个功能拍摄并改变它。但是当我将第一个函数添加到数组时,它没有返回图像。怎么了?在游乐场写了代码,swift ver。 7.3.1。请帮帮我:p

import UIKit

//Sample images initialization
let mous = UIImage(named: "moustache.png")!
let sampleImage = UIImage(named: "sample.png")!

//Moustache Filter
func moustacheMaker() -> UIImage{
    let newSize: CGSize = CGSize(width: 75, height: 75)
    let top: UIImage = mous
    let bottom = sampleImage
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
// Now I draw images to context
bottom.drawInRect(CGRect(origin: CGPoint.zero, size: newSize))
top.drawInRect(CGRect(origin: CGPoint.zero, size: newSize))
// Here I return the new image
let changedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return changedImage
}
class FilterApplier{
    typealias FunctionType = Void -> UIImage
    var filters = [(Int, String, FunctionType)]()
    func add(funcOrder: Int, funcName: String, function: FunctionType) -> FilterApplier{
        filters.append(funcOrder, funcName, function)
        return self
    }
    func runByOrder(){
        filters.sort(){
            return $0.0 < $1.0
        }
        for filter in filters{
            filter.2
        }
    }
}

FilterApplier().add(2, funcName: "Moustache", function: moustacheMaker).runByOrder()

顺便说一下:编译器没有表现得像错误一样。什么都没发生://

1 个答案:

答案 0 :(得分:1)

Evgeny,我意识到这可能就是一个例子。正如Vaca所说,问题只是:

filter.2()

然而,仅供参考,其中许多解决方案之一就是这个......

不要忘记,在Swift中,您必须始终使用Extensions ,出于各种原因以及每行代码:)

Extension UIImage {
  filter(with: [(void)]) {
   for f in with { self = f(self) }
  }
}

然后你可以

testImage.filter(with: [blur, fade, moustache])

但你真正想要的是这样......

[blur, fade, moustache].map({ test = $0(test) })

另请注意,您可以轻松保存这些“订单”。

let userChose = [blur, fade, moustache]

userChose.map({ testA = $0(testA) })
userChose.map({ testB = $0(testB) })

(您可以使用扩展程序test.filter(with: userChose)

执行相同的操作

一旦你开始,你也应该查看syntax的变异功能。