swift - dynamicType + cast to protocol leads to crash -


i have these classes:

appdataprotocol.swift

public protocol appdataprotocol{      var logoimagepath : string! {get}     var logotitle : string? {get}     var logosubtitle : string? {get}      var categories : [mainmenuoption]! {get}      static func contentelements(filter: contentfilter?) -> [contentelement]! } 

appdata.swift

class appdata{     static var shareddata : appdataprotocol!     init(){}  } 

customappdata.swift [class conforms appdataprotocol]

class customappdata: appdata, appdataprotocol { // fulfills appdataprotocol, omitted brevity } 

so these classes given, try dynamically set class variable so:

appdata.shareddata = customappdata() 

and access so:

// need class can call class function let appdata = appdata.shareddata.dynamictype as! appdataprotocol.type  /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/                              /*crash!*/ let contentelements = appdata.contentelements(nil) 

by calling dynamictype on instance stored in class variable of appdata (shareddata) should getting class conforms appdataprotocol, right ? think problem dynamictype returns interface type (i.e. "appdataprotocol") , cannot call on per se. can tell me why doesn't work ?

op seems wish have have class variable holds type (i.e. actual class) conforms protocol, may variable (i.e. hold different types of protocol @ different times).

the problem

class appdata{    static var shareddata : appdataprotocol    init(){} } 

will not compile, shareddata not initialised. 1 fix make implicitly unwrapped, has done in question, trusting when access it will have been set. problem when accesses variable's dynamictype it's not expects - it's implicitlyunwrappedoptional<appdataprotocol>.type rather appdataprotocol.type.

the solution declare static var shareddata : appdataprotocol? rather static var shareddata : appdataprotocol!, , unwrap before calling dynamictype, thus:

let appdata = (appdata.shareddata!).dynamictype // "customappdata.type"

op - feel free edit if assumption intent off target...


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -