Function accepting generic parameters

Function accepting generic parameters



I have a subclass of NSManagedObject. I'm using a protocol to create a "wrapper" class. In my controller the data can be either: Items or Item1. To be able to use my function I'll have to add the protocol ItemInfo to Items but that means I'll have to add


NSManagedObject


Items


Item1


function


ItemInfo


Items


var items: Items return self



in Items, which seems a bit redundant. I've tried creating a base class but that didn't work.


Items



Is there a better way to let my function accept both Items and Item1 as parameter like using generics?


Items


Item1



NSManagedObject:


NSManagedObject


class Items: NSManagedObject

@NSManaged var name: String
@NSManaged var code: String



Protocol:


Protocol


protocol ItemInfo
var item: Items get


extension ItemInfo

var name : String return item.name
var code : String return item.code



Wrapper:


Wrapper


class Item1: ItemInfo
let item: Items

init(item: Items) self.item = item



function:


function


func handleItem(item: ItemInfo)
print(item.name)
print(item.code)



I could use:


func handleItem<T>(item: T)
if let a = item as? Items
print(a.name)
print(a.code)


if let a = item as? ItemInfo
print(a.name)
print(a.code)




But this doesn't seem the right way ...




1 Answer
1



If I understand correctly what you are trying to achieve (function accepting two kind of items), I would use protocol as type accepted by function, refer the code below


class Items: NSManagedObject, ItemInfo

@NSManaged var name: String
@NSManaged var code: String


class Item1: NSManagedObject, ItemInfo

@NSManaged var name: String
@NSManaged var code: String


protocol ItemInfo
var name: String get set
var code: String get set



and function would look like this


func handle(item: ItemInfo)
print(item.code)
print(item.name)






Item1 (or protocol ItemInfo) is just merely a "wrapper" of Items though. Also Items is actually a lot more complicated. I just simplified it here so it's more readable.

– Henny Lee
Sep 16 '18 at 3:05


Item1


ItemInfo


Items


Items



Thanks for contributing an answer to Stack Overflow!



But avoid …



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

.name

Greenpeace

Thomas Howard, 21st Earl of Arundel