这是在XCode 7.3上。
如果我使用优化标志-O
构建代码,它将崩溃。它在没有优化的情况下正常工作(标记-Onone
)。但是我希望我的代码可以通过优化来构建。
是Swift编译器错误吗?
这是代码。
import Foundation
extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
func multipartFormParams(preFix preFix: String = "") -> [String: AnyObject] {
var params: [String: AnyObject] = [:]
for (key, value) in self {
let subKey = preFix != "" ? "\(preFix)[\(key)]" : String(key)
if let value = value as? [String: AnyObject] {
// params += value.multipartFormParams(preFix: subKey) // this is my original code, however remove the operation extension += to focus on the bug.
value.multipartFormParams(preFix: subKey) // It crash here.
} else {
params[subKey] = value
}
}
return params
}
}
let parameters: [String: AnyObject] = [
"user": [
"first_name": "first",
"last_name": "last"
]
]
parameters.multipartFormParams()
答案 0 :(得分:0)
过了一段时间,我发现这与此错误有关:https://bugs.swift.org/browse/SR-1114,将for (key, value) in self {
更改为forEach { key, value in
解决了问题。
完整的工作版本:
import Foundation
extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
func multipartFormParams(preFix preFix: String = "") -> [String: AnyObject] {
var params: [String: AnyObject] = [:]
forEach { key, value in
let subKey = preFix != "" ? "\(preFix)[\(key)]" : String(key)
if let value = value as? [String: AnyObject] {
// params += value.multipartFormParams(preFix: subKey) // this is my original code, however remove the operation extension += to focus on the bug.
value.multipartFormParams(preFix: subKey) // It crash here.
} else {
params[subKey] = value
}
}
return params
}
}
let parameters: [String: AnyObject] = [
"user": [
"first_name": "first",
"last_name": "last"
]
]
parameters.multipartFormParams()