enum Sections: Int {
case parent
case general
}
struct Parent {
let name: String
}
enum General: Int {
case manage
case settings
func title() -> String {
switch self {
case .manage:
return "Manage"
case .settings:
return "Settings"
}
}
}
struct DataProvider {
func data(at index: NSIndexPath) -> ? {
let section = Sections(rawValue: index.section)!
switch section {
case .parent:
print("parent \(Parent(name: "Venkat"))")
return Parent(name: "Venkat")
case .general:
let general = General(rawValue: index.row)!
print(general.title())
return general
}
}
}
这里,func数据(索引:NSIndexPath)需要根据索引路径返回值类型。我尝试使用协议但它需要属性要求来处理单元级别。实现该方法的任何其他方式以及" General"枚举实现
答案 0 :(得分:0)
您可以创建共享父/协议,然后该函数可以返回共享父实例,然后您可以有条件地向下转换。或者您可以让函数返回AnyObject
,这是一个共享父级。
func data(atIndex: NSIndexPath) -> AnyObject {/*implementation*/}
/*
* Later in another function
*/
let someObj = data(atIndex:index)
if let parentObj = someObj as? Parent
{
// Do what you need with the parent object, possibly save it to a parent ref
}
你可以为General
类型做同样的事情。这不是一个超级可扩展的系统,因为如果你想要返回的函数中还有3-4种类型,那么查看它的类型会变得很混乱。
此时虽然您可能希望重新设计代码,但函数的返回类型应尽可能保持不变。