gpt4 book ai didi

ios - 使用 Swift 推断类方法中的泛型类型

转载 作者:可可西里 更新时间:2023-11-01 00:36:14 27 4
gpt4 key购买 nike

泛型方法是否可以根据执行它的类来推断其类型?我使用 CoreData NSManagedObject 模型来存储和检索本地数据,并设法以一种易于阅读和使用的方式使所有内容通用,除了在一个地方。如果用户希望查询本地数据库以获取对象列表,他将编写以下行:

let posts: [Post] = Post.all()

这将正确返回数据库中的“所有”Post 对象,但语法要求在从 [Post] 调用方法之前定义类型 ( Post )类本身( Post.all() ),感觉不必要地多余。有什么方法可以简单地通过调用 all() 来定义泛型类型?来自 Post 的方法类(class)?我想我可以创建全局函数来获取数据,如下所示:

let posts: [Post] = all()

如果语法如下,这感觉几乎没有可读性:

let posts = Post.all()

尝试改进这一点的目的是让任何选择这个项目的开发人员都可以毫不费力地快速学习结构和风格。此外,这有望在未来提高一般代码的可读性,无论是有人在处理它还是出于其他原因阅读它。

为了更深入地了解,这里有一些关于当前结构的更多信息:

//Model.swift - The model base class. All models extend this class.

class Model: NSManagedObject {
/**
Some other stuff here
**/

//MARK: Fetch
internal class func fetch<T: Model>(predicate: NSPredicate? = nil) -> [T]? {
do {
if let request = NSFetchRequest.FromEntityName(self.entityName) { //Get entity with the name defined in the current class
request.predicate = predicate
if let result = try self.context?.executeFetchRequest(request) as? [T] {
return result
}
}
}
catch let error as NSError {
Log.Error("\(error)")
}
return nil
}

//MARK: Fetch general
class func all<T: Model>() -> [T]? {
if let result: [T] = self.fetch() {
return result
}
Log.warning("No \(self.entityName) found")
return nil
}
}

//Post.swift - An example model class. Extends Model.swift

class Post: Model {
//some fields
}

//Example view controller
class ViewController: UIViewController {
override func viewDidLoad() {
let posts: [Post] = Post.all()
//do stuff
}
}

如果有人对此有任何想法,请告诉我。感谢所有帮助!

最佳答案

在一般情况下,即使对于子类,类方法返回“类的类型”的典型方法是使用协议(protocol)扩展和 Self 类型。这是一个将您的方法简化为最低限度以使类型检查按您想要的方式工作的示例:

// define a protocol
protocol ModelType {}
// create a static method on the protocol that returns [Self]
extension ModelType where Self: NSManagedObject {
static func all() -> [Self]? {
return [Self]() // do your fetch here
}
}
// conform to the protocol in your class hierarchy
class Model: NSManagedObject, ModelType {}
class Post: Model {}

let posts = Post.all()
// implicit type of `posts` is `[Post]?`

请注意,all() 应由协议(protocol)扩展提供,但不是协议(protocol)的要求。如果你在 protocol ModelType 中声明了 all(),那么你不能让它使用动态调度,如果它要使用动态类型,这是必需的。


另请注意,在 Swift 3(和 macOS 10.12/iOS 10/tvOS 10/watchOS 3)中,Core Data 本身定义了一些 Swift API 快捷方式,这些快捷方式取代了您为自己定义的一些快捷方式。请注意来自 What's New in Core Data 的示例:

func findAnimals() {
context.performAndWait({
let request = Animal.fetchRequest // implicitly NSFetchRequest<Animal>
do {
let searchResults = try request.execute()
// use searchResults ...
} catch {
print("Error with request: \(error)")
}
})
}

最后,对您选择的样式进行一些评论...

fyi I capitalize the first letter in all static/class methods just as a convention

The point of trying to improve this is so that any developers who pick up this project can quickly learn the structure and style without much effort. Also, this will hopefully increase general code readability in the future

我不确定打破语言标准约定(例如 Swift 3 API Guidelines 中推荐的小写方法名称)是否与您的目标非常一致,即让其他刚接触您的代码库的开发人员能够轻松阅读和参与。

关于ios - 使用 Swift 推断类方法中的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com