【问题标题】:How do i add objects into an array from a Class in Swift?如何将对象从 Swift 中的类添加到数组中?
【发布时间】:2021-12-30 05:24:53
【问题描述】:

这是我的朋友班:

class Friend {
    var firstName: String = ""
    var lastName: String = ""
    var age: Int = 0
    var description:String = ""

    init(firstname: String, lastname: String, age: Int) {
        self.firstName = firstname
        self.lastName = lastname
        self.age = age
    }
}

这是我应该在 viewDidLoad 函数中声明和实例化 5 个 Friend 对象并将它们添加到“friendList”数组中的地方。

import UIKit

class ViewController: UIViewController {

    var friendsList: [Friend] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        friendsList.append("John", "Doe", 20)
    }
}

Swift 在“friendsList.append”行告诉我“在调用实例方法 'append' 时没有完全匹配”。

【问题讨论】:

  • 您的代码中没有任何内容会创建 Friend 对象,您必须在某个地方执行此操作。
  • 你可以在 append 函数中创建你的Friend 例如:friendsList.append(Friend(firstname: "John", lastname: "Doe", age: 20))

标签: arrays swift


【解决方案1】:

如果你最初创建所有朋友,你可以像下面这样使用

 let friends = [Friend(firstname: "John", lastname: "Doe", age: 20),Friend(firstname: "doe", lastname: "John", age: 21)]
    
    for friend in friends{
        friendsList.append(friend)
    } 
//////////////////////////////////////
 (or) you can directly declare value for your global variable  

friendsList = [Friend(firstname: "John", lastname: "Doe", age: 20),Friend(firstname: "doe", lastname: "John", age: 21)]
///////////////////////////////////////////

(or) assign local variable value to your global variable
friendsList = friends

或者如果你逐个添加,你必须先创建对象

  let friendOne = Friend(firstname: "John", lastname: "Doe", age: 20)
    friendsList.append(friendOne)

【讨论】:

    【解决方案2】:

    Array(实际上是集合)函数 append 接受 <T> 类型的参数,其中 T 是泛型类型,“数组中元素的类型”。

    所以如果你有一个字符串数组,你需要将一个字符串传递给 append:

    var strings = [String]()
    
    strings.append("a string")
    

    由于您有一个Friend 对象数组,因此您需要将Friend 的实例传递给append(_:) 函数。您调用 append 时括号内的表达式是否会计算到朋友对象?

    friendsList.append("John", "Doe", 20)
    

    它没有。您正在传递以逗号分隔的属性列表。据推测,这些是Friend 的名字、姓氏和年龄,但append() 函数不知道这些。

    你可以这样写:

    let aFriend = Friend(firstname: "John", lastname: "Doe", age: 20)
    friendList.append(aFriend)
    

    或全部在一行中:

    friendList.append(Friend(firstname: "John", lastname: "Doe", age: 20))
    

    这两种变体都可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2016-08-16
      • 2013-05-14
      • 1970-01-01
      • 2020-02-22
      相关资源
      最近更新 更多