Reputation: 89
I've created some functions with return type Void -> UIImage and I've build a class "FilterApplier" to call function by order. The idea is that every function takes a picture and changes it. But as I added the first function to an array, it did not return the image. What is wrong? Wrote code in a playground, swift ver. 7.3.1. Help me out please :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()
By the way: the compiler does not act like there is a mistake. Nothing happens ://
Upvotes: 0
Views: 190
Reputation: 12296
Evgeny, I realize it was probably just an example. As Vaca said, the problem is just:
filter.2()
However just FYI one of many solutions here would be this...
Don't forget, in Swift you have to use Extensions all the time, everywhere, for all reasons, and in every line of code :)
Extension UIImage {
filter(with: [(void)]) {
for f in with { self = f(self) }
}
}
then you can just
testImage.filter(with: [blur, fade, moustache])
But what you are really perhaps looking for is something like this...
[blur, fade, moustache].map({ test = $0(test) })
note too that you can easily save those "orderings".
let userChose = [blur, fade, moustache]
userChose.map({ testA = $0(testA) })
userChose.map({ testB = $0(testB) })
(You could do the same thing with the extension, test.filter(with: userChose)
)
Once you get going you should check out the syntax for mutating functions, too.
Upvotes: 1