简体   繁体   中英

How to convert String to Struct (in Swift)

I have a struct like,

struct LoginConstants {
  struct Selectors {
    let testa = "test1234"
  }
}

and a class like,

class Login: XCTestCase {
  override class func setUp () {
    // below constant will have a value like "LoginConstants"
    let localConstants = "\(String(describing: self))Constants"

  }
}

... so here I have a struct-name as a string format in localConstants .

My Question is how I can access the LoginConstants properties from the localConstants string?

NOTE: I know I can access the LoginConstants() directly. But I am planning to create a parent class where I can access this ***Constants struct dynamically.

Thanks for the help!

Objective-C has the ability to do this, but Swift does not. If you give a class an Objective-C name via the @objc attribute, you can use the Objective-C runtime functions to access it by name. However, this is not possible with a struct.

It's probably not the best way to go anyway. A better solution is to rethink what you are trying to do, and access the struct type directly rather than by name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM