gpt4 book ai didi

swift - 在元组中追加两个字符串数组

转载 作者:行者123 更新时间:2023-11-30 10:03:13 25 4
gpt4 key购买 nike

我试图在 tuple附加两个Sting Arrays,但它给了我错误? image

这是我的课:

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

现在它给了我这个错误:

enter image description here

如何将元组附加到数组?

最佳答案

[代码已删除]

此外,正如用户在评论中告诉您的那样,命名数组 tuple 是一个坏习惯。 元组这个名字已经更合适了

编辑:正如@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))
}
}
}

关于swift - 在元组中追加两个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37345587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com