[英]Swift 3 Generic infix operator error
在將項目從Xcode 7更新到8的過程中,我遇到了一個問題。
有一個通用的infix
運算符可處理UIView
的約束。
這是運算符的定義:
precedencegroup constPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
infix operator >>>- : constPrecedence
@discardableResult
func >>>- <T: UIView> (left: (T, T), block: (inout ConstraintInfo) -> ()) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
info.secondAttribute = info.secondAttribute == .notAnAttribute ? info.attribute : info.secondAttribute
let constraint = NSLayoutConstraint(item: left.1,
attribute: info.attribute,
relatedBy: info.relation,
toItem: left.0,
attribute: info.secondAttribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.0.addConstraint(constraint)
return constraint
}
現在,在使用運算符時,出現了一個我不明白的錯誤:
for attribute: NSLayoutAttribute in [.left, .right, .top, .bottom] {
(view, self) >>>- {
$0.attribute = attribute
}
}
我也使用非泛型函數進行了測試,它仍然會抱怨該塊的類型。
任何想法?
PS:我不是代碼的原始作者,我正在嘗試為PR更新代碼,並且更改語法會影響太多代碼。
通過在傳遞給操作員的代碼塊的末尾添加一個return
調用,我能夠解決此問題。 看來Swift 3.0編譯器無法推斷出代碼塊是沒有return
的閉包。 正如問題注釋中提到的那樣,原始運算符應該可以在新的Swift 3.0項目中正常工作,但是從較早的Swift版本轉換項目似乎會以某種方式破壞運算符。
無論如何,這是現在運算符的正確用法,並且可以正常工作:
for attribute: NSLayoutAttribute in [.left, .right, .top, .bottom] {
(view, self) >>>- {
$0.attribute = attribute
return
}
}
PS:我之前一直在進行此修復,但是在修復了一些錯誤並且我不知道原因之后,我收到了奇怪的Segmentation Fault error 11
。 事實證明,Xcode無法處理某些閉包類型,並且發生了分段錯誤。 將return
叫添加到使用操作員的所有位置可以解決此問題。
我很樂意與任何感興趣的開發人員討論原因和更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.