快速启动栏
Init() is a method used to initialize values in swift. Swift will not allow you to compile a class without initializing the non-optional values of a class.
Init()是一种用于快速初始化值的方法。 Swift不允许您在不初始化类的非可选值的情况下编译类。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/a39302a19d3f50980a685773cfc150f2.png)
To avoid this error you could initialize above variables with some default value when we create them, like below.
为了避免发生此错误,您可以在创建变量时使用一些默认值初始化上述变量,如下所示。
var myStringValue : String = “Hello”
var myIntValues : Int = 0
But what if you don’t want to assign values to the variables while creating them, you could always make them optional. But creating unwanted optionals are not the right approach, that's where we use Init() method. It can be used to initialize the values of class when creating the object of the class.
但是,如果您不想在创建变量时将值分配给变量,可以始终使它们可选。 但是创建不必要的可选方法不是正确的方法,这就是我们使用Init()方法的地方。 创建类的对象时,可用于初始化类的值。
class initExample{var myStringValue : Stringvar myIntValue : Intinit(myString:String, myInt:Int) {self.myStringValue = myStringself.myIntValue = myInt}}let initObject = initExample(myString: “Hello”, myInt: 10)
This is a basic feature of swift, that is used by developers all the time. Hope I helped.
这是swift的基本功能,开发人员一直在使用它。 希望我能帮上忙。
快速启动栏