Skip to content

Instantly share code, notes, and snippets.

@bewebste
Last active September 30, 2016 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bewebste/d9c2389b32a2e70f263ddee199e977a9 to your computer and use it in GitHub Desktop.
Save bewebste/d9c2389b32a2e70f263ddee199e977a9 to your computer and use it in GitHub Desktop.
Swift 3 generic object wrapper gives EXC_BAD_ACCESS
//: Playground - noun: a place where people can play
import Cocoa
/*
I've been using an object like ObjectWrapper in Swift 2.x without any problems
to store a Swift struct as a property an Objective-C object, and then later
access and use that struct from other Swift code.
Upon upgrading to Swift 3, trying to access the value field of the ObjectWrapper
results in an EXC_BAD_ACCESS. If I de-generecise things, ala PersonWrapper, then
everything works OK. Is this a Swift 3 bug, or something I shouldn't have been able
to do in the first place?
*/
class ObjectWrapper<T> : NSObject {
let value: T?
init(value: T?) {
self.value = value
}
}
class PersonWrapper : NSObject {
let value: Person?
init(value: Person?) {
self.value = value
}
}
struct Person {
let name: String
let age: Int
let country: String
}
let person = Person(name: "Brian", age: 38, country: "USA")
let testWrapper = PersonWrapper(value: person)
var newName: String
if let wrappedPerson = testWrapper.value { //This access works fine
newName = wrappedPerson.name
} else {
newName = "No person"
}
print(newName)
let testWrapper2 = ObjectWrapper(value: person)
if let wrappedPerson = testWrapper2.value { //This gives EXC_BAD_ACCESS
newName = wrappedPerson.name
} else {
newName = "No person"
}
print(newName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment