現在,蘋果已輕鬆擺脫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?'。 –