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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế