Gol*_*ter 8 extension-methods closures runtime properties swift
我想在扩展中添加闭包属性,UITextView所以我使用typealias定义一个闭包:
typealias TextViewHeightDidChangedClosure = (_ currentTextViewHeight:CGFloat)->Void
extension UITextView{
func setTextViewHeightDidChanged(textViewHeightDidChanged:TextViewHeightDidChangedBlock){
objc_setAssociatedObject(self, &TextViewHeightDidChangedBlockKey, textViewHeightDidChanged, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
func textViewHeightDidChanged()->TextViewHeightDidChangedBlock?{
let textChanged : ((CGFloat)->Void) = objc_getAssociatedObject(self, &TextViewHeightDidChangedBlockKey) as! TextViewHeightDidChangedBlock
return textChanged
}
}
Run Code Online (Sandbox Code Playgroud)
但它告诉我一个错误说:
由于信号命令失败:分段错误:11.
这是错误的图像
谁能告诉我为什么,给我一个深刻有意义的解释,非常感谢你!
Ben*_*o85 10
如果Bool!在类中声明属性并尝试使用此属性创建三元条件,也可能会出现此错误:
var isSomething: Bool!
func myFunc() {
let value = isSomething ? "something" : "not"
}
Run Code Online (Sandbox Code Playgroud)
只需添加!在你的财产
var isSomething: Bool!
func myFunc() {
let value = isSomething! ? "something" : "not"
}
Run Code Online (Sandbox Code Playgroud)
通常,使用SegFault 11崩溃是编译器的错误,您最好发送错误报告.
大多数此类错误都可以通过正确修复代码来解决.
代码中最重要的一点是Swift中常见的闭包(@convention(swift)通常省略)不能传递给Objective-C的Any代表id.使用在Swift书中@convention(block)声明为id兼容的(本部分):
typealias TextViewHeightDidChangedBlock = @convention(block) (_ currentTextViewHeight:CGFloat)->Void
Run Code Online (Sandbox Code Playgroud)
您可能已尝试过此操作,但在这种情况下,只是放置@convention(block)并不能解决问题.
似乎需要另一个技巧来使你的代码工作,显式地转换为AnyObject:
extension UITextView{
func setTextViewHeightDidChanged(textViewHeightDidChanged: @escaping TextViewHeightDidChangedBlock){
objc_setAssociatedObject(self, &TextViewHeightDidChangedBlockKey, textViewHeightDidChanged as! AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
func textViewHeightDidChanged()->TextViewHeightDidChangedBlock?{
let textChanged : ((CGFloat)->Void) = objc_getAssociatedObject(self, &TextViewHeightDidChangedBlockKey) as! TextViewHeightDidChangedBlock
return textChanged
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这似乎是一个缺陷id-as-Any.Any代表id应该接受id兼容的封闭.
我不确定苹果会很快解决这个问题,但无论如何,就我测试而言,我上面的代码按预期工作.
| 归档时间: |
|
| 查看次数: |
4989 次 |
| 最近记录: |