[英]Handling two different value types in swift
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
}
}
}
Here, func data(at index: NSIndexPath) needs to return value type based on indexpath. 在这里,func数据(在索引处:NSIndexPath)需要基于索引路径返回值类型。 I tried with protocol but it need property requirement to handle in cell level.
我尝试使用协议,但需要在单元级别处理属性要求。 Any other way to implement the method and also "General" enum implementation
任何其他方法来实现该方法以及“常规”枚举实现
You could make a shared parent/protocol, then the function could return a shared parent instance, which you can then conditionally down cast. 您可以创建一个共享的父代/协议,然后该函数可以返回一个共享的父代实例,然后可以有条件地向下转换。 Or you could have the function return
AnyObject
which is a shared parent. 或者,您可以让函数返回
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
}
And you can do that similarly for the General
type. 您可以对
General
类型执行类似的操作。 This is not a super scalable system because if you have 3-4 more types in a function that you want to return it gets messy with checking which type it is. 这不是一个超级可伸缩的系统,因为如果要返回的函数中有3-4种以上的类型,则在检查它是哪种类型时会感到混乱。
At that point though you would probably want to redesign your code, the return type of function should be constant whenever possible. 在这一点上,尽管您可能希望重新设计代码,但函数的返回类型应尽可能保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.