【发布时间】:2021-07-11 11:22:56
【问题描述】:
我正在寻找使我的代码更干净、更高效的方法。 我有一个“BaseInfo”,它有一些属性,也是“SomeInfo”和“AnotherInfo”类的父类,它们有自己的附加属性。我制作了一个通用函数,可以从 UserDefaults 中保存和获取这些对象。考虑到它应该使用的信息类型,我有使用这些函数保存和加载信息的 ViewController。我想知道有什么方法可以让我的代码更干净,并在我的 ViewContoller 中摆脱那些类型转换。这是我的信息类:
public class BaseInfo: Codable{
var name: String?
init(_ dict: [String: Any]){
name = dict["name"] as? String
}
}
class AnotherInfo: BaseInfo {
var secondName: String?
override init(_ dict: [String : Any]) {
super.init(dict)
secondName = dict["secondName"] as? String
}
required init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
}
class SomeInfo: BaseInfo {
var middleName: String?
override init(_ dict: [String : Any]) {
super.init(dict)
middleName = dict["middleName"]
}
required init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
}
这是我管理信息的班级
protocol InfoManagerProtocol {
static func getInfo(with type: InfoType) -> BaseInfo?
static func saveInfo <T: BaseInfo>(with type: InfoType, info: T)
}
class InfoManager: InfoManagerProtocol {
static func getInfo<T: BaseInfo>(with type: InfoType) -> T? {
if let data = UserDefaults.standard.object(forKey: type.toString()) as? Data, let info = try? JSONDecoder().decode(type.typeOfInfo() as! T.Type, from: data){
return info
}
return nil
}
static func saveInfo<T>(with type: InfoType, info: T) where T : BaseInfo {
if let encodedData = try? JSONEncoder().encode(info){
UserDefaults.standard.setValue(encodedData, forKey: type.toString())
}
}
}
InfoType 枚举:
enum InfoType: Int{
case base = 1
case another = 2
case some = 3
}
extension InfoType{
func toString() -> String{
switch self{
case .base:
return "base"
case .another:
return "another"
case .some:
return "some"
}
}
func typeOfInfo() -> BaseInfo.Type{
switch self{
case .base:
return BaseInfo.self
case .another:
return AnotherInfo.self
case .some:
return SomeInfo.self
}
}
}
还有一些控制器
class ViewCV: UIViewController{
......
// some outlets
var infoType: InfoType? // info
// some func that updates UI
func updateUI(){
let genericInfo = InfoManager.getInfo(info: .infoType)
self.someNameOutletLabel.text = genericInfo.name
self.secondNameOutletLabel?.text = (genericInfo as? AnotherInfo).secondName // here I don't like it
if let someInfo = genericInfo as? SomeInfo{
self.secondNameOutletLabel?.text = someInfo.thirdName // or like here I also don't like
}
}
}
期待其他批评和建议
【问题讨论】:
标签: ios swift generics types type-alias