【发布时间】:2017-01-29 12:32:21
【问题描述】:
我想用自定义运算符和函数编写某种类似流利的 api。这是我正在寻找的示例:
var result = [Section]()
result +++= Section()
.appendTitle(title)
.appendPhotos(photos)
result +++= Section()
.appendSomething(sth)
.appendPhotos(photos)
.appendAnything()
return result
为此,我声明了两个自定义运算符:
infix operator +++{ associativity left precedence 95 }
func +++(lhs : [Section], rhs : Section) -> [Section] {
var result = lhs
result.append(rhs)
return result
}
infix operator +++= { associativity left precedence 95 }
func +++=(inout lhs : [Section], rhs : Section) {
lhs = lhs +++ rhs
}
当然还有 Section 结构的正确扩展:
extension Section {
mutating func appendTitle(title: String?) -> Section {
guard let unwrappedTitle = title
else { return self }
...
return self
}
mutating func appendPhotos(photos: [Photo]?) -> Section {
...
}
...
}
不幸的是,它没有按预期工作......
单独的result +++= Section() 行是正确的,但是当我添加.append 时它不会编译。
第一条消息是:Passing value of type '[Section]' to an inout parameter requires explicit '&'
然后我尝试在result 前面加上一个&(但我从来没有为a += 1 这样做过)还有第二条消息:Cannot use mutating member on immutable value: function call returns immutable value
如果有人能提供帮助,将不胜感激。
我使用的是 Swift 2.2 和 Xcode 7。
【问题讨论】:
标签: ios swift api operators fluent