简体   繁体   中英

How to pass a class type as a function parameter in Swift?

How can i do the following code ?

    func setupFetchResultController<AnyNSManagedObject>(entityToFetch: AnyNSManagedObject) {
    let fetchRequest:NSFetchRequest<entityToFetch> = entityToFetch.fetchRequest()
}


it produce an error with error message:

Use of undeclared type 'entityToFetch'


also when i've tried the following code

    func setupFetchResultController<AnyNSManagedObject>(entityToFetch: AnyNSManagedObject) {
    let fetchRequest:NSFetchRequest<AnyNSManagedObject> = AnyNSManagedObject.fetchRequest()
}


it also produced an error with error message:

Type 'AnyNSManagedObject' does not conform to protocol 'NSFetchRequestResult'

Use generics

func setupFetchResultController<T: NSManagedObject>(entityToFetch: T) {
    let fetchRequest = T.fetchRequest()        
}

or

func setupFetchResultController<T: NSManagedObject>(entityToFetch: T) {
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM