Reputation: 1358
I have defined a CanStack
protocol with an associated type named Item
:
CanStack.swift
// protocol definition
protocol CanStack:
ExpressibleByArrayLiteral, CustomStringConvertible
{
associatedtype Item
var items:[Item] { get }
init()
mutating func push(_ items: [Item])
mutating func pop() -> Item?
}
// protocol extension (default behavior)
extension CanStack {
public var isEmpty: Bool { return items.isEmpty }
// init by array
public init(_ items:[Item]) {
self.init()
self.push(items)
}
// init by variadic parameter
public init(_ items:Item...){
self.init()
self.push(items)
}
// push items by variadic parameter
public mutating func push(_ items:Item...){
self.push(items)
}
}
// conform to ExpressibleByArrayLiteral
extension CanStack {
public init(arrayLiteral items:Item...){
self.init()
self.push(items)
}
}
// conform to CustomStringConvertible
extension CanStack {
public var description: String {
return "["
+ items.map{"\($0)"}.joined(separator:", ")
+ " ⇄ in/out"
}
}
and defined a StackStruct
struct conforming to this protocol, this generic structure has a type parameter Item
(exactly the same name with the associated type above):
StackStruct.swift
public struct StackStruct<Item> {
public private(set) var items = [Item]()
public init() { }
mutating public func push(_ items:[Item]) {
self.items += items
}
@discardableResult
mutating public func pop() -> Item? {
return items.popLast()
}
}
// adopt CanStack protocol
extension StackStruct: CanStack { }
and then I defined another class Stack
confoming to the protocol too:
Stack.swift
public class Stack<Item> {
public private(set) var items = [Item]()
public required init() {}
public func push(_ newItems:[Item]) {
items += newItems
}
@discardableResult
public func pop() -> Item? {
return items.popLast()
}
}
// adopt CanStack protocol
extension Stack: CanStack { }
and I have 3 test cases:
TestCases.swift
func testStackStruct() {
// init
var s1: StackStruct = [1,2,3] // expressible by array literal
var s2 = StackStruct([4,5,6]) // init by array
var s3 = StackStruct(7, 8, 9) // init by variadic parameter
// push
s1.push([4,5]) // array
s2.push(10, 11) // variadic
s3.push(20) // variadic
// pop
for _ in 1...4 { s1.pop() }
s2.pop()
s3.pop()
// print these stacks
example("stack struct", items:[s1,s2,s3])
}
func testStackClass_Var() {
// init
var s4: Stack = [1,2,3] // ⚠️ warning: s4 was never mutated; consider changing to let ...
var s5 = Stack([4,5,6]) // init by array
var s6 = Stack(7, 8, 9) // init by variadic parameter
// push
s4.push([4,5]) // array
s5.push(10, 11) // variadic
s6.push(20) // variadic
// pop
for _ in 1...4 { s4.pop() }
// print these stacks
example("stack class", items: [s4,s5,s6])
}
func testStackClass_Let() {
// init
let s7: Stack = [1,2,3] // expressible by array literal
let s8 = Stack([4,5,6]) // init by array
let s9 = Stack(7, 8, 9) // init by variadic parameter
// push
s7.push([4,5]) // array
s8.push(10, 11) // ⛔ Error: Extra argument in call
s9.push(20) // ⛔ Error: Cannot convert value of type 'Int' to expected argument type '[Int]'
// pop
for _ in 1...4 { s7.pop() }
// print these stacks
example("stack class", items: [s7,s8,s9])
}
and I can run the first test case testStackStruct()
without any problem:
output of testStackStruct()
[1 ⇄ in/out
[4, 5, 6, 10 ⇄ in/out
[7, 8, 9 ⇄ in/out
and run the testStackClass_Var()
case with only a compiler warning:
⚠️ warning: s4 was never mutated; consider changing to let ...
output of testStackClass_Var()
[1 ⇄ in/out
[4, 5, 6, 10, 11 ⇄ in/out
[7, 8, 9, 20 ⇄ in/out
but the testStackClass_Let()
case can't even compile successfully, I got two compiler errors:
s8.push(10, 11) // ⛔ Error: Extra argument in call
s9.push(20) // ⛔ Error: Cannot convert value of type 'Int' to expected argument type '[Int]'
The only difference between the testStackClass_Var()
case and testStackClass_Let()
case is whether I used a var
or let
to declare those stack instances.
I can't figure out where or what I was doing wrong, can somebody help? thanks.
p.s.
my little helper function:
example.swift
import Foundation // string.padding() needs this
// print example
// usage:
// example("test something", items: [a,b,c]) {
// // example code here ...
// }
public func example<T>(
_ title: String, // example title
length: Int = 30, // title length
items: [T]? = nil, // items to print
run: (()->Void)? = nil // example code (optional)
){
// print example title
print(
("----- [ " + title + " ] ")
.padding(toLength: length, withPad: "-", startingAt: 0)
)
// run example
if let run = run { run() }
// print items if provided
if let items = items {
items.forEach{ print($0) }
}
// new line
print()
}
Upvotes: 4
Views: 126
Reputation: 89
but the testStackClass_Let() case can't even compile successfully, I got two compiler errors:
s8.push(10, 11) // ⛔ Error: Extra argument in call
s9.push(20) // ⛔ Error: Cannot convert value of type 'Int' to expected argument type '[Int]'
The only difference between the testStackClass_Var() case and testStackClass_Let() case is whether I used a var or let to declare those stack instances.
It is all about using mutating functions on Swift structs. Here is a detailed answer: Thanks to Natasha-the-Robot
Upvotes: 0
Reputation: 540005
Your
public func push(_ newItems:[Item]) {
is a method of public class Stack<Item>
, which is a reference type, therefore you can call it on a constant:
let s4: Stack = [1,2,3]
s4.push([4,5])
On the other hand, the variadic method
public mutating func push(_ items:Item...)
is an extension method of protocol CanStack
, which can be adopted by structs as well, therefore it requires a variable. That is why
let s8 = Stack([4,5,6]) // init by array
s8.push(10, 11) // Error: Extra argument in call
does not compile.
Here is a shorter example demonstrating the problem:
protocol P {
mutating func foo()
mutating func bar()
}
extension P {
mutating func bar() {}
}
class C: P {
func foo() {}
}
let c = C()
c.foo()
c.bar() // Cannot use mutating member on immutable value: 'c' is a 'let' constant
The underlying reason (as I understand it from the sources listed below) is that a mutating func
called on a reference type is not only allowed to mutate the properties of self
, but also to replace self
by a new value.
It would compile if P
is declared as a class protocol instead (and the mutating
keyword is removed):
protocol P: class {
func foo()
func bar()
}
extension P {
func bar() {}
}
Related resources:
var
declaration of class variables bug report.Upvotes: 3