在Swift中可选包装,为什么Swift会添加" Optional"到字符串

时间:2015-09-08 10:55:26

标签: ios swift optional wrapping

我将数组保存到模型中,当保存数据时没有使用Optional(...)包装,但是当读取数据时,我得到了可选(...)包裹它。感谢您的帮助和耐心,因为我是Swift的新手。

将值添加到模型时,这是TldLocationsCache

println

从模型中读取值时,这是saveOperativesInModel: Test Name

println

为什么Swift会添加" Optional(xxx)"字符串?

这是简化代码:

getOperativesFromModel: Optional(Test Name)

2 个答案:

答案 0 :(得分:4)

Optional出现在控制台中,因为item.valueForKey会返回AnyObject?,这是一种可选类型。由于您在字符串插值段中使用valueForKey值,因此该值将成为可选值。因此,打印到控制台的值是可选的,Swift会自动在控制台中添加Optional()包装器中的可选值。

要避免此行为,您可以:

  • 使用valueForKey(强制解包)运算符强制从!展开值,该运算符如下所示:String(stringInterpolationSegment: item.valueForKey("firstName")!)
  • 使用if let检查值,然后打印出未包装的值。例如:

    if let firstName = item.valueForKey("firstName") {
        operative.firstName = String(firstName)
        println("getOperativesFromModel: \(operative.firstName)")
    }
    

答案 1 :(得分:2)

已经回答为什么你看到"可选(...)"在输出中。 以下是关于如何解决问题的一些额外想法。

你写的原因

operative.firstName = String (stringInterpolationSegment: item.valueForKey("firstName"))

可能是直接分配

operative.firstName = item.valueForKey("firstName")

不编译:rhs的类型为AnyObject?,而 lhs是String

更好的解决方案是可选的演员

if let firstName = item.valueForKey("firstName") as? String {
    operative.firstName = firstName
} else {
    // There is no first name, or it is not a String.
}

或使用nil-coalescing运算符??提供默认值:

operative.firstName = item.valueForKey("firstName") as? String ?? "default name"

但我实际上做的是让Xcode创建NSManaged对象 核心数据实体的子类文件(也许你甚至做过 已经?)。那你就不再需要Key-Value编码方法了 并且可以直接访问实体属性:

let fetchRequest1: NSFetchRequest! = NSFetchRequest(entityName:"Operatives")
let fetchedResults = managedContext.executeFetchRequest(fetchRequest1, error: &error) as? [Operatives]
if let operativesTable = fetchedResults {
    for item in operativesTable {
        let operative = Operative()
        operative.firstName = item.firstName
        println("getOperativesFromModel: \(operative.firstName)")
    }
}