Swift中的可选包装,为什么Swift会添加"Optional"到字符串 [英] Optional wrapping in Swift, why does Swift add the "Optional" to the string

查看:591
本文介绍了Swift中的可选包装,为什么Swift会添加"Optional"到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数组保存到模型中,当保存数据时不使用Optional(...)包装,但是在读取数据时,我得到了Optional(...)包装.在我刚接触Swift时,感谢您的帮助和耐心.

I'm saving an array into a model, when saving the data is not wrapped with Optional (...) however when the data is being read I get the Optional(...) wrapping around it. Appreciate your help and patience as I'm new to Swift.

这是将值添加到模型时的println:

This is the println when adding the values to the model:

saveOperativesInModel: Test Name

这是从模型中读取值时的println:

This is the println when reading the values back from the model:

getOperativesFromModel: Optional(Test Name)

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

Why does Swift add the "Optional(xxx)" to the String?

这是简化的代码:

func saveOperativesInModel() {


    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    let entity =  NSEntityDescription.entityForName("Operatives", inManagedObjectContext: managedContext)

    var item: NSManagedObject!
    if let operativesList = self.operativesResult?.operativesList {
        self.operativesTable.removeAll()
        for itemInArray in operativesList {
            item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
            item.setValue(itemInArray.firstName, forKey: "firstName")
            var error: NSError?
            if !managedContext.save(&error) {
            } else {
                self.operativesTable.append(item!)
                println("saveOperativesInModel: \(itemInArray.firstName)")
            }
        }
    }

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

推荐答案

Optional出现在控制台中是因为item.valueForKey返回了AnyObject?(可选类型).由于在字符串插值段中使用的是valueForKey值,因此该值变为可选.因此,要打印到控制台的值是可选的,并且Swift会在控制台中的可选值周围自动添加Optional()包装器.

The Optional appears in the console because item.valueForKey returns an AnyObject?, an optional type. Since you're using the valueForKey value in your string interpolation segment, that value becomes optional. Therefore, the value being printed to the console is optional, and Swift automatically adds the Optional() wrapper around optional values in the console.

为避免这种现象,您可以:

To avoid this behavior, you can either:

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

  • Force-unwrap the value from valueForKey by using the ! (force unwrap) operator, which would look something like this: String(stringInterpolationSegment: item.valueForKey("firstName")!), or
  • Use if let to check for a value and then print out the unwrapped value. For example:

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

这篇关于Swift中的可选包装,为什么Swift会添加"Optional"到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆