swift - Read static property from object -


i have class static property access specific object. code follows:

import uikit  protocol theme {     static var name: string { }      func getbackgroundcolor() -> uicolor }  class defaulttheme: theme {     static var name = "default theme"      func getbackgroundcolor() -> uicolor {         return uicolor.blackcolor()     } }  var currenttheme: theme = defaulttheme() println(currenttheme.name) //error: 'theme' not have member named 'name' 

i cannot acces theme's name via defaulttheme.name because currenttheme may instance of different theme class, need know it's name. how can access static variable?

i using xcode 6.3.1 (with swift 1.2)

you've hit obscure , interesting bug in swift 1.2. swift has long history of bugs related static variables required protocols, , appears one.

the problem here, apparently, have tried mix , match protocol-based characteristics class-based characteristics. suppose had said this:

var currenttheme = defaulttheme() 

then currenttheme typed defaulttheme - instance of class. means can access class member instance passing thru dynamictype of instance:

println(currenttheme.dynamictype.name) // "default theme" 

but can't in your code, because have typed currenttheme theme - protocol:

var currenttheme : theme = defaulttheme() 

this weird things notion of name property, imposed protocol, , can't access name property @ all.

you not have problem if theme defaulttheme's superclass. in case, use class property (which have computed property) , work polymorphically. in swift 1.2, might best bet:

class theme {     class var name : string { return "theme" } } class defaulttheme: theme {     override class var name : string { return "default theme" } } var currenttheme : theme = defaulttheme() println(currenttheme.dynamictype.name) // "default theme" 

on other hand, when upgrade swift 2, find bug fixed, , print(currenttheme.dynamictype.name) works protocol:

protocol theme {     static var name : string { } } class defaulttheme: theme {     static var name = "default theme" } var currenttheme : theme = defaulttheme() print(currenttheme.dynamictype.name) // "default theme" 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -