我有两个包含Core Image过滤器数组的变量,但它们是我不完全理解的对象(可能是某种闭包吗?):
var filterSet: [CIFilter] = { return [CIFilter1(), CIFilter2(), CIFilter3()] }()
var filterSetAlt: [CIFilter] = { return [CIFilter4(), CIFilter5(), CIFilter6()] }()
稍后在程序中,我使用for
循环运行这些数组中的一个或另一个:
for eachFilter in self.filterSet {
// apply eachFilter to image
我希望能够将另一个变量filterSetPicked
设置为filterSet
或filterSetAlt
,这样我只需要一个for
循环(现在我使用的是if-else
选择要运行的循环,以便我有一堆重复的代码。
当我尝试var filterSetPicked = filterSet
Xcode哭泣时ViewController.Type
没有名为filterSet
的成员 - 我认为这是因为filterSet
语法= { return [...] }()
,看起来有点像我见过的一些例子,但不完全是。
编辑:这是我尝试做的简化版本:
class CIColorChannel1: CIFilter {
var inputImage: CIImage!
override var outputImage: CIImage! {
get {
return CIFilter(name: "CIColorMatrix", withInputParameters: [
kCIInputImageKey : inputImage,
"inputRVector" : CIVector(x: 0, y: 0, z: 0),
"inputGVector" : CIVector(x: 0, y: 0, z: 0),
"inputBVector" : CIVector(x: 0, y: 0, z: 1),
"inputBiasVector" : CIVector(x: 0, y: 0, z: 0),
]).outputImage
}
}
}
class CIColorChannel2: CIFilter {
…
}
class CIColorChannel3: CIFilter {
…
}
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
var filterSet = [CIColorChannel1(), CIColorChannel2()]
var filterSetAlt = [CIColorChannel2(), CIColorChannel3()]
var filterSetPicked = filterSet
func shutterButton() {
for eachFilter in self.filterSetPicked {
// take photo, apply filters
// (this part already works if I just use filterSet or filterSetAlt directly)
}
}
}
但是在尝试设置var filterSetPicked = filterSet
时会抛出错误。
答案 0 :(得分:0)
AFAIK,没有必要用你的例子中的表达式包装你的数组。您可以像这样简化声明:
var filterSet: [CIFilter] = [CIFilter1(), CIFilter2(), CIFilter3()]
您甚至可以在没有类型的情况下声明它,让编译器推断:
var filterSet = [CIFilter1(), CIFilter2(), CIFilter3()]
然后将filterSet
分配给另一个变量(我刚刚在Playground中测试)没有问题:
var filterSetPicked = filterSet
对于你的循环,你可能只需要摆脱self
:
for eachFilter in filterSet {
// do stuff
}
答案 1 :(得分:0)
我仍然不明白为什么我要做的事情不起作用,但我找到了解决办法:
import UIKit
import AVFoundation
class CIColorChannel1: CIFilter {
var inputImage: CIImage!
override var outputImage: CIImage! {
get {
return CIFilter(name: "CIColorMatrix", withInputParameters: [
kCIInputImageKey : inputImage,
"inputRVector" : CIVector(x: 0, y: 0, z: 0),
"inputGVector" : CIVector(x: 0, y: 0, z: 0),
"inputBVector" : CIVector(x: 0, y: 0, z: 1),
"inputBiasVector" : CIVector(x: 0, y: 0, z: 0),
]).outputImage
}
}
}
class CIColorChannel2: CIFilter {
...
}
class CIColorChannel3: CIFilter {
...
}
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
var filterSet = [CIColorChannel1(), CIColorChannel2()]
var filterSetAlt = [CIColorChannel2(), CIColorChannel3()]
var filterSetPicked = []
var filterSetting = true
func shutterButton() {
if self.filterSetting {
self.filterSetPicked = self.filterSet
} else {
self.filterSetPicked = self.filterSetAlt
}
for eachFilter in self.filterSetPicked {
// take photo, apply filters
// (this part already works if I just use filterSet or filterSetAlt directly)
}
}
}