我在Generics中有两个波纹管功能。
func objectFunc<T:SomeProtocol>(obj:T)
func arrayFunc<T:SomeProtocol>(obj:[T])
我可以将这些功能分组到一个功能中吗?
我找到了链接Checking if an object is a given type in Swift,但这有点不同。
加。
例如,我想像贝娄那样做。
func objectAndArrayFunc<T>(arg:T, someEnum:SomeEnum){
switch someEnum {
case A:
// something
case B:
// something
}
if let items = arg as? [T] {
for item in items {
// something
}
} else if let item = arg as? T {
// something
}
// I want to do something [T] and T common processing
}
enum SomeEnum {
case A
case B
}
此外,SomeEnum计数可能会增加。
答案 0 :(得分:0)
一般来说,取决于// something
是什么。有很多方法......
私人通用处理器
protocol Property {
var name: String{ get }
}
enum SomeEnum {
case A, B
}
func process<T:Property>(object:T, someEnum:SomeEnum) {
process(object, nil, someEnum)
}
func process<T:Property>(objects:[T], someEnum:SomeEnum) {
process(nil, objects, someEnum)
}
private func process<T:Property>(object: T?, objects:[T]?, someEnum:SomeEnum) {
switch someEnum {
case .A:
// something
break
case .B:
// something
break
}
// holds all items for common processing
var itemsToProcess: [T] = []
if let items = objects {
// process items
itemsToProcess = items
for item in items {
println("\(item.name)")
}
} else if let item = object {
// process single item
itemsToProcess = [item]
println("\(item.name)")
}
// iterate over single/all items and process them
for item in itemsToProcess {
println("\(item.name)")
}
}
将其包装为枚举
protocol Property {
var name: String{ get }
}
enum SomeEnum {
case A, B
}
enum Objects<T> {
case Single(T)
case Multiple([T])
}
private func process<T:Property>(objects: Objects<T>, someEnum:SomeEnum) {
switch someEnum {
case .A:
// something
break
case .B:
// something
break
}
// holds all items for common processing
var itemsToProcess: [T] = []
switch objects {
case .Multiple(let items):
// process items
itemsToProcess = items
for item in items {
println("\(item.name)")
}
case .Single(let item):
// process single item
itemsToProcess = [item]
println("\(item.name)")
}
// iterate over single/all items and process them
for item in itemsToProcess {
println("\(item.name)")
}
}
struct Prop: Property {
var name: String {
return "hi"
}
}
let prop = Prop()
process(.Single(prop), .A)
process(.Multiple([prop]), .B)
不幸的是,第二个例子是segfaults Swift 1.2编译器。
无论如何,这实际上取决于你的目标是什么。为什么你不希望将单个项目作为[T]
传递,...
要回答您的问题 - 不,您不能在一个参数,不同类型中传递T
或[T]
。除非你确实想要使用Enum
并制作AnyObject
舞蹈,否则将它包装到as
或其他任何内容,...