Cómo usar Swift struct en Objective C


Simplemente tengo una estructura que almacena las constantes de la aplicación como se muestra a continuación:

struct Constant {

    static let ParseApplicationId = "xxx"
    static let ParseClientKey = "xxx"

    static var AppGreenColor: UIColor {
        return UIColor(hexString: "67B632")
    }
}

Estas constantes se pueden usar en código Swift llamando a Constant.ParseClientKey por ejemplo. Pero en mi código, también contiene algunas clases de Objective C. Así que mi pregunta es ¿cómo usar estas constantes en el código de Objective C?

Si esta manera de declarar constantes no es buena, entonces ¿cuál es la mejor manera de crear constantes globales para ser utilizadas tanto en el código Swift como en el código Objective C ?

Author: Dinh Quan, 2014-10-03

3 answers

Es triste decirlo, no se puede exponer struct, ni variables globales a Objective-C. ver la documentación.

A partir de ahora, en mi Humilde opinión, la mejor manera es algo como esto:

let ParseApplicationId = "xxx"
let ParseClientKey = "xxx"
let AppGreenColor = UIColor(red: 0.2, green: 0.7, blue: 0.3 alpha: 1.0)

@objc class Constant: NSObject {
    private init() {}

    class func parseApplicationId() -> String { return ParseApplicationId }
    class func parseClientKey() -> String { return ParseClientKey }
    class func appGreenColor() -> UIColor { return AppGreenColor }
}

En Objective-C, puedes usarlos así:

NSString *appklicationId = [Constant parseApplicationId];
NSString *clientKey = [Constant parseClientKey];
UIColor *greenColor = [Constant appGreenColor];
 83
Author: rintaro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-03 21:05:08
//Why not create a file something like this: 

import UIKit
import Foundation

extension UIColor {
    convenience init(hex: Int) {
        let components = (
            R: CGFloat((hex >> 16) & 0xff) / 255,
            G: CGFloat((hex >> 08) & 0xff) / 255,
            B: CGFloat((hex >> 00) & 0xff) / 255
        )

        self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
    }
}

extension CGColor {
    class func colorWithHex(hex: Int) -> CGColorRef {
        return UIColor(hex: hex).CGColor
    }
}

struct Constant {

    static let kParseApplicationId = "5678"
    static let kParseClientKey = "1234"

    static var kAppGreenColor: UIColor { return UIColor(hex:0x67B632) }

    static var kTextBlackColor: UIColor { return UIColor(hex:0x000000) }
    static var kSomeBgBlueColor: UIColor { return UIColor(hex:0x0000FF) }
    static var kLineGrayCGColor: CGColor { return CGColor.colorWithHex(0xCCCCCC) }
    static var kLineRedCGColor: CGColor { return CGColor.colorWithHex(0xFF0000) }
}


@objc class Constants: NSObject {
    private override init() {}

    class func parseApplicationId() -> String { return Constant.kParseApplicationId }
    class func parseClientKey() -> String { return Constant.kParseClientKey }
    class func appGreenColor() -> UIColor { return Constant.kAppGreenColor }

    class func textBlackColor() -> UIColor { return Constant.kTextBlackColor }

    class func someBgBlueColor() -> UIColor { return Constant.kSomeBgBlueColor }

    class func lineGrayCGColor() -> CGColor { return Constant.kLineGrayCGColor }

    class func lineRedCGColor() -> CGColor { return Constant.kLineRedCGColor }
}

//for use in Objective-C files add this when you need to use constants:  
//#import "ProjectModuleName-Swift.h"

//Swift usage: 
//self.view.backgroundColor = Constant.kAppGreenColor


//Objective-C file: 
//self.view.backgroundColor = [Constants appGreenColor];

//This way you can update colors, default text, web service urls for whole app in one place. 

//just an idea on this thread.
 8
Author: Marijan V.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-27 23:04:58

Debe hacer que las sentencias let sean privadas si desea hacer otros tipos Swift en su código para acceder a estas constantes solo a través de clase:

private let AppGreenColor = UIColor(red: 0.2, green: 0.7, blue: 0.3 alpha: 1.0)

@objc class Constant {
    class func appGreenColor() -> UIColor { return AppGreenColor }
}

En Swift, puedes usarlos así:

UIColor *greenColor = Constant.appGreenColor

La siguiente línea ya no se compilará ya que la instrucción let es privada:

UIColor *greenColor = appGreenColor
 0
Author: koira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 16:21:42