Swift 2.2 - 代码崩溃,除非我关闭优化(-Onone)

时间:2016-09-07 07:22:46

标签: ios swift macos recursion

这是在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()

1 个答案:

答案 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()