简体   繁体   English

我们如何将 Objective-C 常量导入为 Swift 类型?

[英]How we can Import Objective-C Constants as Swift Types?

I want to declare constant in Swift 3 .我想在Swift 3声明常量。 For example if we have following constant in Objective-C :例如,如果我们在 Objective-C 中有以下常量:

HK_EXTERN NSString * const HKQuantityTypeIdentifierHeight;
HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyMass;

Add New Swift file : Constant.swift添加新的 Swift 文件: Constant.swift

import Foundation
import HealthKit

let HK_EXTERN_Height : NSString = HKQuantityTypeIdentifierHeight
let HK_EXTERN_BodyMass : NSString = HKQuantityTypeIdentifierBodyMass

Use in ViewController.swiftViewController.swift 中使用

print(HK_EXTERN_Height)
print(HK_EXTERN_BodyMass)

Hope this help you....希望这对你有帮助......

Adding constants into a separate file is also possible in Swift.在 Swift 中也可以将常量添加到单独的文件中。

For using constants, it is even smarter, if you use structs , because huge number of constants can be messy:对于使用常量,如果使用structs聪明,因为大量的常量可能会很混乱:

import HealthKit

struct Constants {

    struct Health {

        struct Quantities {
            let height : NSString = HKQuantityTypeIdentifierHeight
            let bodyMass : NSString = HKQuantityTypeIdentifierBodyMass
            static let minWeight: Double = 30.0
        }  
        ...          
    } 
    ...
}

Usage:用法:

print(Constants.Health.Quantities.minWeight)

or或者

let healthNumbers = Constants.Health.Quantities
print(healthNumbers.minWeight)

我相信在 Swift 语言中,您可以使用 let 关键字进行声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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