class func shareString(title : String, array: [AnyObject]) -> String {
var strValue: String!
//strValue = "\(title)"
for i in 0...array.count-1 {
let share:[String: String?] = array[i] as! [String : String?]
strValue = "\n\n \(strValue), \n\n \(share["title"]) \n\n\(share["value"])"
}
return strValue!
}
//Optional("\n\n Optional(\"\\n\\n nil, \\n\\n Optional(Optional(\\\"\\\\n LayFlat\\\")) \\n\\nOptional(Optional(\\\"252.0\\\"))\"), \n\n Optional(Optional(\"\\n Die Diameter\")) \n\nOptional(Optional(\"25.0\"))"),
Optional(Optional("\n Output"))
Optional(Optional("6.42096"))
回答
當你下標時它已經返回可選項,你正在設置值爲String?
的字典意味着你得到兩次可選的指定AnyObject數組使其成爲[[String:String]]
的數組,因此不需要再次將它轉換爲字母。還用空字符串初始化了strValue
。
var strValue = ""
if let dicArray = array as? [[String:String]] {
for dic in dicArray {
if let title = dic["title"], let value = dic["value"] {
strValue += "\n\n \(title) \n\n\(value)"
}
}
}
使用可選鏈接像波紋管
strValue中=「\ n \ n(strValue中?? 「」),\ n \ n (股[ 「標題」] - 「」) \ n \ n(股[ 「值」] - 「」)」
使用力展開變量,如果它有值
strValue中= 「\ n \ n(strValue中!),\ n \ n(股[」 標題 「]!) \ n \ n(股[」 值 「]!)」
'strValue!'由於OP沒有初始化strValue –
for i in 0...array.count-1 {
let share:[String: String?] = array[i] as! [String : String?]
if let title = share["title"], let value = share["value"]{
print("title: \(title) , Value: \(value)")
//output: title: 252.0 , Value: Die Diameter
}
}
'title','value'仍然是'optionals',因爲字典的類型是'[String:String?]'意味着value是可選的你需要包裝可選的兩次 –
你應該使用正確的swift模式,所以例如用於數組{ ......如果let elem as? [字符串:字符串?] {.. – ingconti
- 1. 我已經寫了這段代碼使用正則表達式去除字符串,可以優化嗎?
- 2. 如何使用NSRegularExpression從字符串中刪除子字符串?
- 3. 如何從HTML字符串中刪除代碼?
- 4. 如何從字符串中刪除BB代碼?
- 5. 如何從一個字符串中刪除PHP代碼?
- 6. 如何從字符串中刪除無效的代碼點?
- 7. 如何從javascript中的字符串中刪除以下文本?
- 8. 如何在Windows下從我的代碼中刪除字體?
- 9. 我已經刪除它們後,如何從Xcode提示符中刪除文件?
- 10. 我可以重置選擇框,我已經刪除選項與JavaScript/jQuery?
- 11. 如何使用xslt從字符串中刪除字符?
- 12. 從字符串的可選點中刪除一個字符
- 13. 尋找使用preg_replace從我的字符串中刪除字符
- 14. 我可以從字符串
- 15. PHP代碼字符串替換特殊字符刪除字符
- 16. 如何使用Python從字符串中刪除符號?
- 17. 從字符串中刪除字符串
- 18. 從字符串中刪除字符串
- 19. 如何從字符串中刪除'<'?
- 20. 如何從字符串中刪除\」
- 21. 如何從字符串中刪除'quote?
- 22. 的Android如何刪除( 「)從字符串
- 23. 如何使用Regex.Replace從字符串中刪除數字?
- 24. 如何刪除字符串?
- 25. 從字符串末尾刪除已知字符
- 26. 使用javascript從字符串(URL)中刪除子字符串(URL)
- 27. 如何解碼以下字符串
- 28. 我應該如何從我的字符串URL刪除+(SWIFT)
- 29. 如何從字符串中刪除子字符串
- 30. 如何從字符串的末尾刪除子字符串
你需要使用,如果讓或警衛讓刪除可選 –
如果讓分享:[String:String?] = array [i] as使用! [String:String?] {.....} –
我簡單地使用!和我的問題解決了類func shareString(標題:字符串!,數組:[AnyObject]) - >字符串{stripe { var strValue:String! strValue中= 「\(標題!)」 如果array.count> 0 { 對於i在0 ... array.count-1 { 設份額:[字符串:字符串] =陣列[I]作爲! 「( 」!(股\ [標題] 「![值])」:[字符串字符串] strValue中=共享)「 \ n \ n \(!strValue中)\」 } } 返回strValue中! } –