I've written a protocol and corresponding extension which utilizes a simple StringStack
in tandem with a naming convention of the form "<origin>@<destination>"
to perform segues between nested views in my Swift application. I'm new to swift so if there's a better way to implement what are essentially forward and back buttons across multiple views, I'm open to it. However the following code is problematic for reasons I detail below.
struct StringStack {
var stack: Array = [String]()
mutating func push(str: String)->Void {
self.stack.append(str)
}
mutating func pop()->String {
self.stack.popLast()
}
}
protocol SegueForwardAndBackward {
var thisIdentifier: String {get set}
var segueStack: StringStack {get set}
}
extension SegueForwardAndBackward where Self: UIViewController {
mutating func performForwardSegue(nextIdentifier: String) {
let identifier: String = thisIdentifier + "@" + nextIdentifier
segueStack.push(identifier)
performSegueWithIdentifier(identifier, sender: self)
}
mutating func performBackwardSegue() {
let divided = segueStack.pop().componentsSeparatedByString("@")
// reverses destination and origin of identifier
let segueIdentifier: String = divided[1] + "@" + divided[0]
performSegueWithIdentifier(segueIdentifier, sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if var destinationViewController: SegueForwardAndBackward = segue.destinationViewController as? SegueForwardAndBackward {
destinationViewController.segueStack = segueStack
}
}
}
My initial problem is that mutating functions aren't allowed in protocol extension as detailed in this bug report. There is a proposed workaround given in that report however the following results in an error claiming that 'SegueForwardAndBackward' is not a subtype of 'UIViewController'
.
class A: UIViewController, SegueForwardAndBackward {
mutating func testFunc() {
var p: SegueForwardAndBackward = self
p.performBackwardSegue()
}
}
I did come across a potential solution where I could make SegueForwardAndBackward
a class protocol as detailed in another question. However, implementing a class protocol results in a segfault, which I presume is because I declare my extension to be where Self: UIViewController
, and unfortunately I've no clue how to resolve this.
At the moment I'm quite frustrated with what appears to be yet another bug in Swift, so any help in reworking my approach, or deciphering these errors would be much appreciated.
Thanks in advance for your response!