簡體   English   中英

我們如何將 Objective-C 常量導入為 Swift 類型?

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

我想在Swift 3聲明常量。 例如,如果我們在 Objective-C 中有以下常量:

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

添加新的 Swift 文件: Constant.swift

import Foundation
import HealthKit

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

ViewController.swift 中使用

print(HK_EXTERN_Height)
print(HK_EXTERN_BodyMass)

希望這對你有幫助......

在 Swift 中也可以將常量添加到單獨的文件中。

對於使用常量,如果使用structs聰明,因為大量的常量可能會很混亂:

import HealthKit

struct Constants {

    struct Health {

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

用法:

print(Constants.Health.Quantities.minWeight)

或者

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

我相信在 Swift 語言中,您可以使用 let 關鍵字進行聲明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM