objective-c 如何在swift中声明一个可以在目标c中使用的常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24237129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to declare a constant in swift that can be used in objective c
提问by user2909913
if I declare the swift constant as a global constantlike:
如果我将 swift 常量声明为全局常量,例如:
let a = "123"
but the acannot be found in objective c.
但是a在目标 c 中找不到。
How to solve this?
如何解决这个问题?
回答by Yatheesha B L
From Apple Doc:
来自苹果文档:
You'll have access to anything within a class or protocol that's marked with the @objc attribute as long as it's compatible with Objective-C. This excludes Swift-only features such as those listed here:
- Generics
- Tuples
- Enumerations defined in Swift
- Structures defined in Swift
- Top-level functions defined in Swift
- Global variables defined in Swift
- Typealiases defined in Swift
- Swift-style variadics
- Nested types
- Curried functions
只要与 Objective-C 兼容,您就可以访问标有 @objc 属性的类或协议中的任何内容。这不包括仅 Swift 的功能,例如此处列出的功能:
- 泛型
- 元组
- Swift 中定义的枚举
- Swift 中定义的结构
- Swift 中定义的顶级函数
- Swift 中定义的全局变量
- Swift 中定义的类型别名
- Swift 风格的可变参数
- 嵌套类型
- 咖喱函数
Therefore its not possible to access global variables(Constants) or global functions defined in Swift.
因此无法访问 Swift 中定义的全局变量(常量)或全局函数。
Possible Solutions:
可能的解决方案:
From the Apple Document Swift programming language, You can Declare Type Properties as
class var constant: Int = { return 10 }()But currently in Swift(beta-3) Type propertiesare not supported.
You can declare a Class function to get a constant value:
In Swift:
class func myConst() -> String { return "Your constant" }
在 Apple Document Swift 编程语言中,您可以将类型属性声明为
class var constant: Int = { return 10 }()但目前在 Swift(beta-3)中不支持Type 属性。
你可以声明一个 Class 函数来获取一个常量值:
在斯威夫特:
class func myConst() -> String { return "Your constant" }
Accessing from Objective-C:
从 Objective-C 访问:
NSString *constantValue = [ClassName myConst];
NSLog(@"%@", constantValue);
回答by Gee.E
Swift code:
SWIFT代码:
public class MyClass: NSObject {
public static let myConst = "aConst"
}
and then in Objective-C:
然后在Objective-C中:
[MyClass myConst]
Isn't this working as well? As in this works for me.
这不是也有效吗?因为这对我有用。
Also this is somewhatshorter as creating a object first (alloc, init). Making a new function for everyconstant is... not pretty :/
此外,这比首先创建一个对象要短一些(alloc, init)。为每个常量创建一个新函数是......不漂亮:/
Update for Swift 4
Swift 4 更新
Because of the changes in Swift 4's Objective-C inference, you need to add the @objcannotation to the declared constant as well. The previous declaration then becomes:
由于 Swift 4 的 Objective-C 推理中的更改,您还需要将@objc注释添加到声明的常量中。之前的声明然后变成:
@objcMembers
public class MyClass: NSObject {
public static let myConst = "aConst"
}
The calling Objective-C code remains the same.
调用Objective-C 代码保持不变。
Using
@objcMembersmakes all constants available (as if you'd write@objcbefore each constant), but I've had times where the compiler somehow wouldn't generate the corresponding ObjC code.In those cases I'd suggest adding the
@objcdecorator before the constant as well.
I.e.:@objc public static let myConst = "aConst"
Using
@objcMembers使所有常量都可用(就像您@objc在每个常量之前编写一样),但我有时编译器以某种方式不会生成相应的 ObjC 代码。在这些情况下,我建议
@objc在常量之前添加装饰器。
IE:@objc public static let myConst = "aConst"
回答by Jose Manuel Abarca Rodríguez
You should not have any problem by using letin Objective-C, next example was made with Xcode 7.2 :
let在 Objective-C 中使用应该没有任何问题,下一个示例是使用 Xcode 7.2 制作的:
MyClass.swift
MyClass.swift
import Foundation
import UIKit
@objc class MyClass : NSObject { // <== @objc AND NSObject ARE BOTH NECESSARY!!!
let my_color = UIColor( red:128/255,green:32/255,blue:64/255,alpha:1 ) // <== CONSTANT!!!
}
MyObjectiveC.m
我的目标C.m
#import "PROJECTNAME-Swift.h" // <== NECESSARY TO RECOGNIZE SWIFT CLASSES!!!
@interface MyObjectiveC ()
@end
@implementation MyObjectiveC
@synthesize tableview; // <== ANY UI OBJECT, JUST AS EXAMPLE!!!
- (void) viewDidLoad () {
MyClass * mc = [ [ MyClass alloc ] init ]; // <== INSTANTIATE SWIFT CLASS!!!
tableview.backgroundColor = mc.my_color; // <== USE THE CONSTANT!!!
}
@end
PROJECTNAMEis the name of your Xcode project, as shown in Project Navigator.
PROJECTNAME是 Xcode 项目的名称,如项目导航器中所示。
回答by alicanbatur
In your swift class,
在你快速的课堂上,
let constant: Float = -1
class YourClass: NSObject {
class func getMyConstant() -> Float {return constant}
...
}
Clean, build to let xcode prepare this method useable for obj-c. Then at your obj-c class
清理,构建让 xcode 准备这个可用于 obj-c 的方法。然后在你的 obj-c 课上
if ([YourClass getMyConstant] != 0) {
...
}
回答by nasli
First of all you need to know about the important of auto-generated Swift header file.
首先,您需要了解自动生成的 Swift 头文件的重要性。
It is the one that will made the magicto transcribe the Swift code to be understandable from Objective-C.
正是这一点使将Swift 代码转录为可从 Objective-C 中理解的魔术。
This file is auto-generated by Xcode (do not look for itin your project).
这个文件是由 Xcode 自动生成的(不要在你的项目中寻找它)。
The important of this file is to use the correct name, it can match with your target name, but, may not, it is the product module name. (Search for it in your project settings as "Product module")
此文件的重要之处在于使用正确的名称,它可以与您的目标名称匹配,但也可能不是,它是产品模块名称。(在您的项目设置中将其搜索为“产品模块”)
You need to import this fileon the Objective-C class that you want to use a Swift class and also the Swift class nameof your Swift file.
你需要在你想要使用 Swift 类的 Objective-C 类上导入这个文件,以及你的 Swift 文件的 Swift 类名。
#import <ProductModuleName-Swift.h>
@class MySwiftClassName;
My Swift class should have the prefix @objcand inherit from NSObject:
我的 Swift 类应该有前缀@objc并继承自NSObject:
@objc class MySwiftClassName: NSObject {
let mySwiftVar = "123"
}
Then you can call your Swift variable from the Objective-C file:
然后你可以从 Objective-C 文件中调用你的 Swift 变量:
MySwiftClassName *mySwiftClassO = [[MySwiftClassName alloc] init];
NSString *myVar = mySwiftClassO.mySwiftVar;
Make sure to clean and rebuildyour project after each change to force regenerate this auto-generated file.
确保在每次更改后清理并重建您的项目以强制重新生成此自动生成的文件。
If your Swift header file was auto-generated correctly you can navigate to it by clicking over the import file name and check if all the code you need was properly transcribed.
如果您的 Swift 头文件是正确自动生成的,您可以通过单击导入文件名来导航到它,并检查您需要的所有代码是否都已正确转录。
In the following post you can find more detailed information about this. https://solidgeargroup.com/bridging-swift-objective-c
在下面的帖子中,您可以找到有关此内容的更多详细信息。https://solidgeargroup.com/bridging-swift-objective-c
回答by oskarko
Classes func don't work. The only solution I have found out is this one:
类 func 不起作用。我发现的唯一解决方案是这个:
class YourController: NSObject {
@objc static let shared = YourController()
private override init() { }
@objc class func sharedInstance() -> YourController {
return YourController.shared
}
@objc let terms = "Your-String-here"
And then on Obj-c file:
然后在 Obj-c 文件上:
[[YourController sharedInstance].terms]

