通过数组删除变量

时间:2017-04-22 09:49:07

标签: arrays swift

我正在尝试删除数组中很多变量的值:

var fbUserID = String()
var fbUserName = String()
var meNickname = String()
var userIDOneSignal = String()

var deleteStrings = [fbUserID, fbUserName, meNickname, userIDOneSignal]

是否有可能做到这一点:

for i in deleteStrings {
    i.removeAll()//remove all as in remove the values of each variable
}

我也尝试过使用deleteStrings[i].removeAll()

4 个答案:

答案 0 :(得分:3)

由于值语义,你不能改变数组中的变量(作为指针)。

而不是数组使用结构

struct User {

    var fbUserID = "12"
    var fbUserName = "Foo"
    var meNickname = "Baz"
    var userIDOneSignal = "123"

    mutating func clear()
    {
        fbUserID = ""
        fbUserName = ""
        meNickname = ""
        userIDOneSignal = ""
    }
}

var user = User()
print(user.fbUserID) // "12"
user.clear()

user.fbUserID = ""
print(user.fbUserID) // ""

答案 1 :(得分:0)

只需删除数组元素

即可
deleteStrings.removeAll()

答案 2 :(得分:0)

如果您的class继承自NSObject,则可以使用key value coding按姓名访问字段:

class User: NSObject {
    var fbUserID = String()
    var fbUserName = String()
    var meNickname = String()
    var userIDOneSignal = String()

    var deleteStrings = ["fbUserID", "fbUserName", "meNickname", "userIDOneSignal"]

    func clearAll() {
        deleteStrings.forEach { setValue("", forKey: $0) }
    }
}

let user = User()
user.fbUserID = "12345"
user.fbUserName = "Joseph Doe"
user.meNickname = "Joe"

print(user.meNickname)  // "Joe"

user.clearAll()

print(user.meNickname)  // ""

答案 3 :(得分:-1)

如果你想删除/删除变量值,那么使用optional,否则你的变量值只有在超出范围时才会被删除或变得不存在。

例如:

var a: Int? = 5  // it have default value 5
a = nil // Now a have nil which is kind of telling that it contains nothing which is what you want to achieve

现在回答你的问题。

  

是否有可能做到这一点:

for i in deleteStrings {
    i.removeAll()   
}

您正在迭代字符串数组,然后对于每个字符串,您尝试删除所有characters。首先,你会得到错误

 error: cannot use mutating member on immutable value: 'i' is a 'let' constant

即使你正确使用var它也无法实现你想要做的事情,即I want to delete the variables value,因为你的fbUserID ...所有其他变量仍然会包含你初始化的数据的副本用。

现在该怎么做?

  • 您可以使用可选项来实现它。

    var fbUserID: String? = String()
    var fbUserName: String? = String()
    var meNickname: String? = String()
    var userIDOneSignal: String? = String()
    
    // To delete you will need to assign them nil
    fbUserId = nil
    

同样,你不能在循环中执行它们,因为var是值类型,当你将它添加到列表时,它们的副本就会被添加。