[英]Access structure in Swift array
我可以从ViewController访问应用程序委托中定义的数组内的结构吗?
我收到错误:'Any'在XCode 6.2中没有名为'title'的成员
访问数组内部结构的语法是什么?
//AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
struct TodoItem {
var title: String
}
var todoItem = TodoItem(
title: "Get Milk")
var myArray: [Any] = []
然后在ViewController中
//
// ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
//here I'm adding the struct to the array
let myTodoItem = delegate.myArray.append(delegate.todoItem)
//how do I access the items in the struct?
println(delegate.myArray[0].title)
您的问题是您明确告诉该数组包含Any
对象。 键入数组为MyStruct
类型,它工作正常:
var myArray: [MyStructure] = [];
或者,如果你不能修改数组声明,强制转换:
myValueIWannaRead = (myArray[0] as MyStruct).myValueIWannaRead
您可以定义数组以存储所需的类型:
var myArray: [TodoItem] = [];
然后,您可以正确访问实例。
Any
类型表示未知类型的对象(类/基元类型),并且在编译期间无法知道所访问的实例将是哪种类型。
在Swift中,始终尽可能具体。
如果数组仅包含TodoItem
类型的TodoItem
,则分别声明它。
var myArray: [TodoItem] = []
Any
是一种占位符,编译器不知道它是什么动态类型。
为什么必须将struct TodoItem
添加到AppDelegate? 在我看来,最好在你拥有视图控制器的同一个文件中创建它,或者 - 更好的是 - 创建一个名为TodoItem.swift的新Swift文件来保存结构。
然后将结构移动到新文件或View Controller文件内部,但在ViewController类之外。 你可以打电话:
let myTodoItem = TodoItem(title: "Get Milk") // declaring TodoItem
var myTodoItemArray : [TodoItem] = [] // declaring TodoItem array
myTodoItemArray.append(myTodoItem) // Appending to the array
// then you can set it by calling the array only member
let todoItem = myTodoItemArray[0] as! TodoItem
let title = todoItem.title
// Or you can just call the toDo Item itself
let title = myTodoItem.title
如果你想在两个不同的类之间传递这些数据,我建议使用通过创建协议的委托或使用NSNotifications的通知 。
我乐于助人,快乐编码。
编辑:修复了代码中的一些小错误
解决方案1:你的结构是在AppDelegate类下定义的,所以你必须像这样解析它;
//** Swift 1.2, xCode 6.3.1**//
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
//here I'm adding the struct to the array
delegate.myArray.append(delegate.todoItem)
//how do I access the items in the struct?
println((delegate.myArray[0] as! AppDelegate.TodoItem).title)
解决方案2:将数组Any的数据类型更改为TodoItem
var myArray: [TodoItem] = []
然后,它会起作用;
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
//here I'm adding the struct to the array
delegate.myArray.append(delegate.todoItem)
//how do I access the items in the struct?
println(delegate.myArray[0].title)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.