Reputation: 3501
Is it really forbidden to use if...let
inside closures in Swift 3? Xcode constantly gives me Swift Compiler Error / Command failed due to signal: Segmentation fault: 11
when I put it in a closure.
import Foundation
class ItemsManager: NSObject {
fileprivate let networking: Networking
init(networking: Networking) {
self.networking = networking
}
func fetchItems() {
networking.fetchItemsSuccess({ [weak self] (responseObject: Any) in
// the line below causes "Segmentation fault: 11"
if let itemDictionaries = responseObject as [Dictionary] {
// ...
}
// ...
}, failure: { [weak self] in
// ...
})
}
}
UPDATE 1
While the current class is in swift, Networking
is written in Objective-C, where responseObject
is declared as id
. Swift treats it as Any
.
UPDATE 2
I checked a type of the responseObject
in runtime, it appears to be __NSArrayI
. Is it normal?
Upvotes: 1
Views: 1201
Reputation: 3084
import Foundation
class ItemsManager: NSObject {
fileprivate let networking: Networking
init(networking: Networking) {
self.networking = networking
}
func fetchItems() {
networking.fetchItemsSuccess({ [weak self] responseObject in
if let itemDictionaries = responseObject as [[String: AnyObject]] {
// ...
}
}) { [weak self] in
// ...
}
}
}
This is how I would write this function. (I like using trailing closures like what I did.)
The type of what is returned is inferred from the function definition so placing anything there might just confuse the compiler. Removing extraneous details became a big thing in Swift 3, so that could be your error.
The next thing is that Dictionary
is a [String: AnyObject]
by nature. There are ways of type defining a Dictionary
using the word Dictionary
, but why bother when we can define it directly.
Upvotes: 1