[背景]
折腾:
[已解决]Swift中如何定义NSArray数组指针类型变量
期间,代码:
let buttons:UnsafePointer<NSArray> = tabButtonsContainerView?.subviews |
出错:
Cannot convert value of type ‘[UIView]?’ to specified type ‘UnsafePointer<NSArray>’
如图:
[解决过程]
1.改为:
let buttons:UnsafeMutablePointer<[UIView]> = tabButtonsContainerView?.subviews |
结果出错:
Cannot convert value of type ‘[UIView]?’ to specified type ‘UnsafeMutablePointer<[UIView]>’ (aka ‘UnsafeMutablePointer<Array<UIView>>’)
2.再改为:
let buttons:UnsafeMutablePointer<UIView[]> = tabButtonsContainerView?.subviews |
结果:
Array types are now written with the brackets around the element type
3.再改为:
var buttons:UnsafeMutablePointer<[UIView]> = tabButtonsContainerView?.subviews |
还是出错:
Cannot convert value of type ‘[UIView]?’ to specified type ‘UnsafeMutablePointer<[UIView]>’ (aka ‘UnsafeMutablePointer<Array<UIView>>’)
4.参考:
Using Swift with Cocoa and Objective-C (Swift 2): Interacting with C APIs
并没有看到:
关于 是数组类型的 指针的 定义的写法。。。
5.试试:
var buttons:UnsafeMutablePointer<Array<UIView>> = tabButtonsContainerView?.subviews |
结果出错:
Cannot convert value of type ‘[UIView]?’ to specified type ‘UnsafeMutablePointer<Array<UIView>>’
6.突然有点明白了:
此处,即使是:
(tabButtonsContainerView?.subviews的)[UIView]?
也是和
(UnsafeMutablePointer<Array<UIView>>)的UnsafeMutablePointer<Array<UIView>>
是不一样的类型
-》想办法,弄成一样的类型,就可以了。
所以去试试:
最后改为:
var buttons:UnsafeMutablePointer<[UIView]> = UnsafeMutablePointer<[UIView]>((tabButtonsContainerView!.subviews))
终于通过编译,没有错误了。。
[总结]
此处的:
不论是任何的两种类型不一样,Swift都会报错的
-》估计连[UIView]和[UIView?]可能都算是不一样的,都会报错
-》所以解决办法就是:
想尽一切办法,把:
Swift中报错的两种类型,变成同一种类型
此处就是把:
let buttons:UnsafePointer<NSArray> = tabButtonsContainerView?.subviews
其中:
前面的类型是:UnsafePointer<NSArray>
后面的类型是:[UIView]?
改为:
var buttons:UnsafeMutablePointer<[UIView]> = UnsafeMutablePointer<[UIView]>((tabButtonsContainerView!.subviews))
使得前后都是 UnsafeMutablePointer<[UIView]> 类型,就可以了。
转载请注明:在路上 » [已解决]Swift代码出错:Cannot convert value of type [UIView]? to specified type UnsafePointer<NSArray>