在objC中,
NSString *stringValue = @"123s";
NSInteger *intValue = [stringValue integerValue];
NSLog(@"intergerValue %@",intValue);
if(!intValue)
{
NSLog(@"caught null object");
}
else
{
// Do appropriate operation with the not null object
}
打印" interValue(null)" "捕获了空对象"
如果条件允许,则使用!(not)运算符安全地完成绑定...
但是,在swift中,使用可选变量的等效片段是
var normalValue : String = "123s"
var optionalValue = normalValue.toInt()
println("optionvalue \(optionalValue)")
if optionalValue {
// Do appropriate operation with the not nil value
}
else{
println("caught null object")
}
这"可选绑定"也是在objectiveC中完成的,那么具有可选变量/常量的确切用法是什么。并且还说过我们可以避免返回null对象而不是返回nil值。返回null对象时会出现什么问题,是否会导致性能问题? 你有效的想法......
答案 0 :(得分:0)
可选类型背后的意图是让程序员创建可能没有值的变量。它是Objective-C中的默认模型,在Swift中已被颠倒,因为语言要求变量默认具有值。
Objective-C通过指针引用所有对象(因此在类型名称后面是星号*
)。由于允许所有指针都没有值(即nil
),因此可以将所有Objective-C对象视为可选对象,即相应的变量可能根本没有任何值。
由于Swift在源代码级别上不需要C兼容性,因此语言设计者选择要求对象具有指定类型的值,并且支持通过可选类型创建可能没有值的变量。