现在,苹果已轻松摆脱NSString
和String
自动兼容性,我有一点噩梦在两者之间。我得到几个NSString
出去了一本字典的,我无法将它们转换为普通String
小号...Swift 1.2 Xcode 6.3 NSString?给字符串给线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x20)
我已经试过:
let fileNameString: String = String(format: "%@", filename!)
let fileNameString: String = (filename as! String)
let fileNameString = filename as? String
let fileNameString = (filename as? String) ?? ""
if let fileNameString = filename as? String {
println("\(fileNameString)")
}
但所有产生错误。
我在转换点打破了,可以看到无论是NSString的零:
但随着要么没有喜悦。获取Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)
。我在这里错过了很明显的东西吗
即使只是试图打印转换导致相同的错误面前..
之前发布的代码转换的尝试,看看是否有什么关系呢?
// First we create a head request as the info I need is in the headers
var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: request.URL!)
newRequest.HTTPMethod = "HEAD"
var response: NSURLResponse?
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)
// Unwrap response as httpResponse in order to access allHeaderFields
if let httpResponse = response as? NSHTTPURLResponse {
let headerString = "sfn-Document-Filename"
let headerNSString = headerString as NSString
let filetypeString = "Content-Type"
let filetypeNSString = filetypeString as NSString
// This is a dictionary where the keys are NSCFStrings
// (NSStrings, hence creating the NSStrings above)
var allHeaders = httpResponse.allHeaderFields
// Getting the filename out here only works with as? NSString. as? String creates the same error as converting.
let filename = allHeaders[headerNSString] as? NSString
// This is a string which contains the type as 'application/pdf' for example. We only need the part after the /.
// Again, trying to get this out as a String fails
let typeString = allHeaders[filetypeNSString] as? NSString
var typeArray = typeString?.componentsSeparatedByString("/") as! [NSString]
let filetype = typeArray[1]
}
将NSString转换为字符串不需要再强制下载,因此只能使用'filename作为字符串'。关于你的问题文件名是什么类型? –
什么是文件名? – user3182143
@zellb Xcode告诉我它需要它,因为它是'NSString?'。 –