找不到成员<方法名称>对于 Swift 中的结构类型 [英] Could not find member <method name> for struct type in Swift
问题描述
我有以下代码,但是当我尝试使用以下 x.initial(2).flatten()
进行链接时,出现编译错误,提示 Could not find member flatten代码>
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
我做错了什么.为了确保我可以继续链接,我在每个链接的方法(例如 flatten、initial 等)之后返回 self.
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
推荐答案
这是因为 initial
返回了 $
的不可变实例.然后,您尝试对其调用变异方法 (flatten
).为了再次改变它,你必须将它存储在另一个可以改变的变量中.您也可以将其更改为 class
而不是 struct
,因为类是可变的.
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.
注意目前,您收到的错误消息很糟糕,但这就是目前 Swift 的生活.
Note currently, the error message you are getting is terrible, but that is life with Swift at the moment.
这篇关于找不到成员<方法名称>对于 Swift 中的结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!