【问题标题】:Swift variables not imported to Objective CSwift 变量未导入到 Objective C
【发布时间】:2017-01-03 00:51:56
【问题描述】:

我正在使用一个基于 Swift 的项目并导入了一些 Objective C 文件。现在我希望我的 Swift 代码可以在 ObjC 文件中运行。一切顺利,但不幸的是,Objective C 类无法使用类的 Int、Float 和 Double 属性。知道为什么这不对Objective C开放吗?

Swift 类:

class Station: NSObject, NSCoding {

    var Id : Int!
    var placeId : Int!
    var name : String!
    var stationDescription : String!
    var uuid : String!
    var major : Int?
    var minor : Int?
    var coordinates: CLLocationCoordinate2D!
    var geoFenceRadius : Float?
    var questions : [Question]?


    }

Swift-Interface 生成类:

@interface Station : NSObject <NSCoding>
@property (nonatomic, copy) NSString * _Null_unspecified name;
@property (nonatomic, copy) NSString * _Null_unspecified stationDescription;
@property (nonatomic, copy) NSString * _Null_unspecified uuid;
@property (nonatomic, copy) NSArray<Question *> * _Nullable questions;
- (BOOL)isEqual:(id _Nullable)object;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
- (nonnull instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
- (void)encodeWithCoder:(NSCoder * _Nonnull)aCoder;
+ (Station * _Nullable)stationWithDictionary:(NSDictionary<NSString *, id> * _Nonnull)dict placeUUID:(NSString * _Nullable)placeUUID;
+ (NSArray<Station *> * _Nullable)parseListFromDictionariesList:(NSArray<NSDictionary<NSString *, id> *> * _Nonnull)dicts placeUUID:(NSString * _Nullable)placeUUID;
@end

这是访问对象 ID 时的错误。

【问题讨论】:

  • 向我们展示您的代码 sn-p 和错误日志(如果有)。
  • @Saad : 你在 swift 中是否在 class 之前使用 @objc 关键字?
  • @Poles 不。但是现在试过了,还是不行。
  • 找到原因了。目标没有替代 Int 这就是为什么不导入
  • @Saad:我不这么认为。删除Int! 中的!Float? 中的? 并观察差异。 – 另见stackoverflow.com/questions/24221407/…

标签: ios objective-c swift xcode


【解决方案1】:

我刚刚尝试过,我的整数被导入为 NSInteger(使用 Xcode 8.2.1 和 Swift 3.0.1)。无论如何,我认为使用 Id 作为变量名是个坏主意,原因有两个:1)在 Swift 中,你应该使用非大写的变量名; 2) Id 与 Obj-C 保留关键字 id 非常相似。尝试将您的变量重命名为 itemID 之类的名称。同时删除!在变量名之后并用 0 初始化它们,如下所示:

class Station: NSObject, NSCoding {

var itemID : Int = 0
var placeId : Int = 0
var name : String!
var stationDescription : String!
var uuid : String!
var major : Int = 0
var minor : Int = 0
var coordinates: CLLocationCoordinate2D!
var geoFenceRadius : Float = 0.0
var questions : [Question]?


}

正如 Martin 之前指出的,这会导致您的所有问题。

【讨论】:

  • tomo 会检查它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2014-07-28
相关资源
最近更新 更多