我有一个单独的结构来保存我的引号数组,我想我会添加多达100个引号,并希望在一个单独的文件中使用它。我试图从我的HomeScreen视图控制器访问此数组,但是不断收到错误“类型为'NSArray'的值没有成员'indices'”。我开始认为我没有采取正确的方法来实现这一目标。
class Quotes: NSObject {
let quotes: NSArray = ["quote1", "quote2","quote50", "quote100"]
}
class HomeScreen: UIViewController {
var quotes: NSArray = NSArray()
func getNextQuote(){
let defaults = UserDefaults.standard
defaults.integer(forKey: "savedIndexKey")
let currentIndex = defaults.integer(forKey: "savedIndexKey")
var nextIndex = currentIndex+1
nextIndex = quotes.indices.contains(nextIndex) ? nextIndex : 0 //error here
defaults.set(nextIndex, forKey: "savedIndexKey")
let savedInteger = defaults.integer(forKey: "savedIndexKey")
saved = savedInteger
quotesLabel.text = quotes[savedInteger]
}
}
override func viewDidLoad() {
var quotesArray: Quotes = Quotes()
quotes = quotesArray.quotes
}
答案 0 :(得分:4)
根本不要在Swift中使用NS...
集合类型。
替换
let quotes: NSArray = ["quote1", "quote2","quote50", "quote100"]
使用
let quotes = ["quote1", "quote2","quote50", "quote100"]
并替换
var quotes: NSArray = NSArray()
使用
var quotes = [String]()