Skip to content

Instantly share code, notes, and snippets.

@smic
Last active May 18, 2016 10:26
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 smic/1ea82daf22074927f16c0c8458368b85 to your computer and use it in GitHub Desktop.
Save smic/1ea82daf22074927f16c0c8458368b85 to your computer and use it in GitHub Desktop.
protocol Copyable {
func copy() -> Self
}
class Class1: Copyable {
var variable1: String
init(variable1: String) {
self.variable1 = variable1
}
func copy() -> Self {
return Class1(variable1: self.variable1)
}
}
class Class2: Class1 {
var variable2: String
init(variable1: String, variable2: String) {
self.variable2 = variable2
super.init(variable1: variable1)
}
override func copy() -> Self {
return Class2(variable1: self.variable1, variable2: self.variable2)
}
}
let var1: Class1 = Class2(variable1: "Bla", variable2: "Blub")
var1.copy()
protocol Copyable {
init(_ instance: Self)
}
extension Copyable {
final func copy() -> Self {
return Self.init(self)
}
}
class Class1: Copyable {
var variable1: String
init(variable1: String) {
self.variable1 = variable1
}
required init(_ instance: Class1) {
self.variable1 = instance.variable1
}
}
class Class2: Class1 {
var variable2: String
init(variable1: String, variable2: String) {
self.variable2 = variable2
super.init(variable1: variable1)
}
required init(_ instance: Class2) {
self.variable2 = instance.variable2
super.init(instance)
}
required init(_ instance: Class1) {
fatalError("Invalid instance")
}
}
let var1: Class1 = Class2(variable1: "Bla", variable2: "Blub")
var1.copy()
protocol Copyable {
func copy() -> Self
}
func copycast<T>(obj: AnyObject) -> T {
return obj as! T
}
class Class1: Copyable {
var variable1: String
init(variable1: String) {
self.variable1 = variable1
}
func copy() -> Self {
return copycast(Class1(variable1: self.variable1))
}
}
class Class2: Class1 {
var variable2: String
init(variable1: String, variable2: String) {
self.variable2 = variable2
super.init(variable1: variable1)
}
override func copy() -> Self {
return copycast(Class2(variable1: self.variable1, variable2: self.variable2))
}
}
let var1: Class1 = Class2(variable1: "Bla", variable2: "Blub")
var1.copy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment