Swift: instance of an object by name

I like to instantiate a class only by class name

here is an example of code from the playground

import Cocoa public protocol FCoding : class { init(coder aDecoder: FCoder) func encodeWithCoder(aCoder: FCoder) } // just some func for demo public protocol FCoder { func encodeString(strv: String?, forKey key: String) func decodeStringForKey(key: String) -> String? } class TestCoder : FCoder { var name = "TestCoder" init () {} func encodeString(strv: String?, forKey key: String) {} func decodeStringForKey(key: String) -> String? { return "111" } } class Test : FCoding { var text : String required init(coder aDecoder: FCoder) { var value = aDecoder.decodeStringForKey("1") if value != nil { text = value! } else { text = "!!!" } } func encodeWithCoder(aEncoder: FCoder) { aEncoder.encodeString(text, forKey: "1") } } var testCoder = TestCoder() let className = NSStringFromClass(Test) let objClass = NSClassFromString(className) as! FCoding.Type //let obj = objClass(coder: testCoder) 

If I uncomment the last statement, the compiler crashes with the error segmenation: 11 (in Xcode version 6.3.1 (6D1002))

  • Is there any other way to implement this?
  • Is there a mistake in the code?
  • Do you have the same problem?

There is a discrepancy in a similar topic: Fast language NSClassFromString

The significant difference is that we are talking about a class of the Swift class (and not a subclass of NSObject), which by default does not have an init method.

+2
swift
May 7 '15 at 21:06
source share
1 answer

The problem seems to be fixed in Swift 2.0 (tested in Beta 2 Xcode)

The following call delivers an instance:

 let obj = objClass.init(coder: testCoder) 
0
Jun 24 '15 at 9:33
source share



All Articles