我创建一个子视图数组
var subviews = self.navigationController?.navigationBar.subviews
“ subviews”变量的类型为“ AnyObject”。我尝试得到子视图:
var subview=subviews[0]
但我收到一个错误:
'[AnyObject]?' does not have a member named 'subscript'
如何访问数组的元素?
最佳答案
该表达式:
self.navigationController?.navigationBar.subviews
返回一个可选参数,因此您必须在使用可选参数之前将其与可选数组拆开:
var subviews = self.navigationController?.navigationBar.subviews
if let subviews = subviews {
// Better check for array length before accessing to the 1st element
var subview = subviews [0]
}
建议阅读:Optionals
关于ios - 在Swift中访问任何对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26210732/