2014-09-05 26 views
4

我在我的.m文件中定義了一些常量,我需要從我的swift代碼中訪問這些常量。它們的定義:從Swift中訪問在Objective-c .m文件中定義的全局常量CGFloat

const CGFloat testValue = 40.0; 

,並在我的其他目標c .m文件,我可以用extern訪問它們:

extern const CGFloat testValue 

有來自.swift文件訪問使這些常數的等效方式?

+0

看看這個頁面:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html – ColGraff 2014-09-05 15:45:36

回答

13

extern添加到您的bridging header並且Swift應該能夠訪問它。

這個簡單的測試工作對我來說:

ObjCTest.m

#import <Foundation/Foundation.h> 

const CGFloat testValue = 40.0; 

ObjCSwiftBridgeTest橋接-Header.h

#import <Foundation/Foundation.h> 

extern const CGFloat testValue; 

main.swift

println(testValue); 

輸出

40.0 
+0

邊注意:如果它是一個對象(例如一個字符串),我不得不刪除關鍵字「靜態」它的工作。 – 2014-12-05 14:11:45

+2

這很奇怪,我有我的'.h'定義並通過橋接頭導入,但它不起作用。在橋接頭中明確重新定義它可以修復它。你會認爲這是導入點?看起來像一個錯誤。 – 2015-01-27 21:02:34

+0

我只需要在Xcode 7.3.0中有'extern'。出於某種原因,Xcode 7.3.1和7.2.1都可以正常工作。 – 2016-05-16 19:53:19

0

只要將var聲明放在類之上 - 它將成爲一個全局變量。

相關問題