[英]Why does a value suddenly become nil?
I'm working on a project where I want to get an image for a particular identifier. 我正在一个项目中,我要获取特定标识符的图像。 I have the following function: 我有以下功能:
func imageForIdentifier(identifier: String?) -> UIImage? {
if identifier == nil || identifier! == "" {
return nil
}
let directory = directoryForID(identifier!)
if let img = imgInCache.objectForKey(identifier!) as? UIImage {
return img
}
if let img = NSData(contentsOfFile: directory) {
return UIImage(data: img)
}
return nil
}
...and the directoryForID
function... ...以及directoryForID
函数...
func directoryForID(identifier: String) -> String {
let directoryPath: NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentationDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first!
return (directoryPath.URLByAppendingPathComponent(identifier).path!)
}
If I pass an image identifier it should create a directory and in the last if-Statement it should return a UIImage
of the data from this directory. 如果我传递图像标识符,它应该创建一个目录,并在最后的if语句中,它应该从该目录返回数据的UIImage
。 However it skips all of the if-Statements and returns nil. 但是,它将跳过所有的if-Statements并返回nil。 How is this possible even though I pass a correct identifier? 即使我传递了正确的标识符,这怎么可能?
Thank you in advance. 先感谢您。
The reason is how you are testing the nil-ability or emptiness of the string object identifier : 原因是您如何测试字符串对象标识符的 空 性或空性:
identifier.length can be helpful to validate the content of the identifier... identifier.length可能有助于验证标识符的内容...
Edited answer. 编辑答案。
func imageForIdentifier(identifier: String?) -> UIImage? {
guard let identifier else { return }
let directory = directoryForID(identifier)
if let img = imgInCache.objectForKey(identifier) as? UIImage {
return img
}
if let img = NSData(contentsOfFile: directory) {
return UIImage(data: img)
}
return nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.