I'm watching a video on classes and the instructor inserts the following code:
class Employee {
var name = ''"
var salary = 0
var role = ""
}
let c: Employee = Employee()
I would like to know what's going on in the line of code in which I declare the constant. It says that c is of the custom data type Employee. But why am I repeating that after the assignment operator, coupled with the parentheses?
I'm assumingthat the parentheses are meant to house the parameters for name, salary, etc as assigned to the class when I intiially defined it. But why am I repeating the name "Employee"? Is that always the case when you create an instance of a class? Should I always expect to have to write the name twice, once without the parntheses and once with them?
Also, if Employee is the custom data type or class, what does Employee() represent? Does that represent the object itself, ie the instance?
Employee() is a special function called initializer. You can think of it as a function that returns Employee. So if you have other functions that also return Employee, say:
/// A function that takes Int and return Employee
func something(parameter: Int) -> Employee {
// I omit the content here, but you get the idea
}
then you can call that function, and get the resulting Employee.
let d: Employee = something(parameter: 4)
The other part is Employee after variable name. It designates the type of variable. In Swift, you can usually omit them since compiler can infer the type from context. So what you wrote is equivalent to
let c = Employee() // We know that Employee() returns `Employee`, so we can omit the type of `c`
We have that in case the compiler can't infer the type, or infer to be the wrong one.
let someInt = 32 // Compiler infers to be int
let someDouble: Double = 32 // Compiler is forced to use `Double` here
PS:
you have a wrong quotation mark, that's why the code above has weird color.
var name = "" // here
Because Swift uses a pair of double quote (") to denote beginning and the ending of String. Since you used single quote ('), the String then begins at the end of line, never ends.
class Employee {
var name = ""
var salary = 0
var role = ""
}
vs
class Employee {
var name = ''"
var salary = 0
var role = ""
}