问题
I have the following code but when I try to chain using the following x.initial(2).flatten()
I get a compile error saying Could not find member flatten
What am I doing wrong. To make sure I can keep chaining I am returning self after each chained method such as flatten, initial, etc.
struct $ {
var resultArray: AnyObject[] = []
init(array: AnyObject[]) {
self.resultArray = array
}
mutating func first() -> AnyObject? {
return $.first(self.resultArray)
}
mutating func flatten() -> $ {
self.resultArray = $.flatten(self.resultArray)
return self
}
static func first(array: AnyObject[]) -> AnyObject? {
if array.isEmpty {
return nil
} else {
return array[0]
}
}
mutating func initial() -> $ {
return self.initial(1)
}
mutating func initial(numElements: Int) -> $ {
self.resultArray = $.initial(self.resultArray, numElements: numElements)
return self
}
func value() -> AnyObject[] {
return self.resultArray
}
static func flatten(array: AnyObject[]) -> AnyObject[] {
var resultArr: AnyObject[] = []
for elem : AnyObject in array {
if let val = elem as? AnyObject[] {
resultArr += self.flatten(val)
} else {
resultArr += elem
}
}
return resultArr
}
static func initial(array: AnyObject[]) -> AnyObject[] {
return self.initial(array, numElements: 1)
}
static func initial(array: AnyObject[], numElements: Int) -> AnyObject[] {
var result: AnyObject[] = []
for (index, _) in enumerate((0..array.count - numElements)) {
result += array[index]
}
return result
}
}
var x = $(array: [[1, 2], 3, [[4]]])
var y = x.initial(2).flatten() //Throws the error
回答1:
It is because initial
returns an immutable instance of $
. You are then trying to call a mutating method (flatten
) on it. In order to mutate it again, you will have to store it in another variable that can be mutated. You could also change it to be a class
instead of a struct
because classes are mutable.
Note currently, the error message you are getting is terrible, but that is life with Swift at the moment.
来源:https://stackoverflow.com/questions/24175774/could-not-find-member-method-name-for-struct-type-in-swift