Reputation: 5967
In a swift lesson I'm going through it says this is a valid way of creating an instance of a class:
class Heroes
{
var (name, gender, kingdom) = ("","","")
var (level, ad, hp) = (0,0,0)
init(name: String)
{
self.name = name
}
}
The part below is what is causing this error "cannot assign value of type '(name: String)' to type 'Heroes'
let sirGeorge: Heroes
sirGeorge = (name: "Sir George")
The below way works fine but I don't understand the syntax of the way above, nor does the compiler. Is there a new way in Swift 3 of writing this perhaps?
var sirLance = Heroes(name: "Sir Lancelot")
Upvotes: 0
Views: 99
Reputation: 24341
Line 1: let sirGeorge: Heroes
Here you are creating a constant sirGeorge
of type Heroes
. This is correct. The only value sirGeorge
can take must be of type Heroes
and nothing else.
Line 2: sirGeorge = (name: "Sir George")
Here you are assigning sirGeorge
a value that is of type (name: "Sir George")
and not Heroes
. So in order to assign value to sirGeorge
you need to create an instance of Heroes
,i.e,
sirGeorge = Heroes(name: "Sir George")
This will call the init(name: String
) of Heroes
.
Upvotes: 0
Reputation: 50
when you do this sirGeorge = (name: "Sir George") is like you want to assign (name: "Sir George") to sirGeorge which is wrong because sirGeorge is an object of class Heroes
So this is the right way
sirGeorge = Heroes(name: "Sir George")
because now you are initialising your object. It is like calling init(lets say init function ) and init takes a String "Sir George"
Upvotes: 0
Reputation: 9136
Because if you want to create the object Heroes, first you need to use the Class Name Heroes then the parenthesis with its arguments (name: "Sir George"), like so:
let sirGeorge: Heroes
sirGeorge = Heroes(name: "Sir George")
Upvotes: 1
Reputation: 15512
let sirGeorge: Heroes
You create constant with let
and name sirGeorge
and you set that type of the constant is Heroes
. It is value reference data type.
sirGeorge = (name: "Sir George")
Second line you try to assign to constant with type Heroes
new value that content type '(name: String)'
and hear you receive issue. Because you're type is Heroes
and not '(name: String)'
. In another hand you try to assign to value constructor of the class.
Upvotes: 0