dart 如何不使用swift初始化类的必需参数?[duplicate]

4si2a6ki  于 2023-01-03  发布在  Swift
关注(0)|答案(1)|浏览(97)

此问题在此处已有答案

Swift how to create and test an object with nil properties?(3个答案)
昨天关门了。
我希望类中的一个变量是可选的,但如果不传递类中的所有变量,我就无法做到这一点。
在变量中定义一个默认值,它可以工作,但我不知道它是否正确。

var studentOne = Student(name: "Unnamed 1", degree: "test") //it works
var studentTwo = Student(name: "Unnamed 2") //not work, how do i accept this?
studentTwo.printValues()

class Student{
    var name : String?
    var degree : String?
    
    init(name : String, degree: String ) {
        self.name = name
        self.degree = degree
    }

    func printValues(){
        print("name: \(name) and \(degree)")
    }
}

我想做的更多的是类似这样的事情,我用dart语言来做,在swift中是怎么做的?

void main() {
  
  var student = Student(name: "Unnamed", degree: "new value");
  var student2 = Student(name: "Only name");
  
  student.printValues();
  student2.printValues();
}

class Student {
  String? name;
  String? degree;
  
  Student({
    this.name,
    this.degree
  });
  
  void printValues(){
    print("Name $name and $degree");
  }
}
tvz2xvvm

tvz2xvvm1#

解决这个问题的一个简单方法是在构造函数中添加一个默认值。Example Preview

class Student {
  var name: String?
  var degree: String?

  init(name: String, degree: String? = nil) {
    self.name = name
    self.degree = degree
  }

  func printValues() {
    // handle value by if_let or set optional value
    print("name: \(name) and \(degree)")
  }
}

或者,在这种情况下,您需要执行构造函数重载。Example Preview

class Student {
  var name: String?
  var degree: String?

  init(name: String, degree: String) {
    self.name = name
    self.degree = degree
  }

  init(name: String) {
    self.name = name
  }

  func printValues() {
    // handle value by if_let or set optional value
    print("name: \(name) and \(degree)")
  }
}

相关问题