Swift -检查未包装可选变量的nil



我有一个模型类如下,这是在Objective-C编写的库。我正在我的swift项目中使用这个类。很快它就变成了String!型的性质。有时这个属性是nil。因此,我正在测试nil验证,如下所示:

Vendor.h

@interface Vendor: NSObject {
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *middleName;
}

在我的Swift项目中,我正在检查midlename属性的nil验证,如下所示:

if anObject.middleNam != nil { // Here, It throws runtime error: fatal error: Unexpectedly found nil while unwrapping an Optional value
}

它抛出了以下运行时错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

如果objective-C属性在swift中暴露为String?,那么我将使用以下内容:

if let middleName = anObject.middleName {
}

如何检查未包装的可选变量。

如果你想让objective - c属性在Swift中被暴露为可选的,用_Nullable标记它,比如

@property (nonatomic, strong) NSString * _Nullable middleName;

现在midlename名称将是可选的类型String?而不是String!,您可以有条件地展开它。

阅读更多关于ObjC

正如Anil所提到的,最好的解决方案是编辑objective-c代码以添加一些_Nullable。但是,据我所知,你的Objective-C代码是一个库,你不能编辑。所以,你必须处理这些可以变成nilString!

但是你可以简单地使用if let技术,像这样:

if let firstName = vendor.firstName {
    print("Here is my firstName: (firstName)")
} else {
    print("I have no firstName")
}
if let middleName = vendor.middleName {
    print("Here is my middleName: (middleName)")
} else {
    print("I have no middleName")
}
if let lastName = vendor.lastName {
    print("Here is my name: (lastName)")
} else {
    print("I have no lastName")
}

使用Vendor代码,它返回以下结果:

@interface Vendor: NSObject
    @property (nonatomic, strong) NSString *firstName;
    @property (nonatomic, strong) NSString *lastName;
    @property (nonatomic, strong) NSString *middleName;
@end
@implementation Vendor
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.firstName = @"Julien";
        self.middleName = nil;
        self.lastName = @"Quere";
    }
    return self;
}
@end
结果:

Here is my firstName: Julien 
I have no middleName 
Here is my name: Quere

相关内容

  • 没有找到相关文章

最新更新