我想在append
中Sting
两个Arrays
tuple
,但它给了我错误?
这是我的班级:
import UIKit
var tuple : [(String, String)] = []
class ViewController: UIViewController , UICollectionViewDelegate{
let reuseIdentifier = "cell"
var url : [String] = []
var image : [String] = []
override func viewDidLoad(){
}
override func viewWillAppear(animated: Bool) {
for i in tuple{
url.append(i.0)
image.append(i.1)
print("URL values.............. \(url)")
print("Image values.............. \(image)")
}
NSUserDefaults.standardUserDefaults().setObject(url, forKey: "u")
NSUserDefaults.standardUserDefaults().setObject(image, forKey: "i")
NSUserDefaults.standardUserDefaults().synchronize()
var u = NSUserDefaults.standardUserDefaults().objectForKey("u")
var i = NSUserDefaults.standardUserDefaults().objectForKey("i")
tuple.removeAll()
tuple.append(u,i)
}
当我将类型更改为:
var u : String = NSUserDefaults.standardUserDefaults().objectForKey("u") as! String
var i : String = NSUserDefaults.standardUserDefaults().objectForKey("i") as! String
现在它给了我这个错误:
如何将元组附加到数组?
答案 0 :(得分:1)
[删除了代码]
此外,正如用户在评论中告诉您的那样,命名数组tuple
是一个坏习惯。名称tuples
已经更好了
编辑:正如@ originaluser2所说,你也可以使用tuple.append((u,i))
EDIT2:我认为这绝对是你要找的(我也调整了名字以避免混淆,你也应该这样做)
import UIKit
class ViewController: UIViewController , UICollectionViewDelegate{
let reuseIdentifier = "cell"
var tuples: [(String, String)] = []
var urls: [String] = []
var images: [String] = []
override func viewDidLoad(){
}
override func viewWillAppear(animated: Bool) {
for i in tuples {
urls.append(i.0)
images.append(i.1)
print("URL values.............. \(urls)")
print("Image values.............. \(images)")
}
NSUserDefaults.standardUserDefaults().setObject(urls, forKey: "u")
NSUserDefaults.standardUserDefaults().setObject(images, forKey: "i")
NSUserDefaults.standardUserDefaults().synchronize()
// Cast objects as NSArray, since it's a subclass of NSObject
// Only NSObject derivate classes can be used for these purposes
let u = NSUserDefaults.standardUserDefaults().objectForKey("u") as! NSArray
let i = NSUserDefaults.standardUserDefaults().objectForKey("i") as! NSArray
tuples.removeAll()
// For every element of the first NSArray
for index in 0 ..< u.count {
// Append in the tuples array the strings at position index
// of both array
// NSString and String class are bridged, so you can use them both
// in order to accomplish your needs. An NSArray btw can store NSString, but not String objects
tuples.append((u.objectAtIndex(index) as! String,i.objectAtIndex(index) as! String))
}
}
}