Reputation: 411
in Swift, why does this code yields an error :
URL(string:"string a”)!.appendPathComponent(“string b”)
error : 'Cannot use mutating member on immutable value: function call returns'
while this code works :
var url: URL=URL(string: "string a")!
url.appendPathComponent(“string b")
Upvotes: 1
Views: 991
Reputation: 6213
Yes ofcourse this happens. because you are trying to change the value which is immutable and it is impossible.
you can see that URL() is struct(value) type, and it's initializer URL(string: )
returns you immutable copy.
you said that this below code is working.
var url: URL=URL(string: "string a")!
url.appendPathComponent(“string b")
Because, your are creating the mutable copy of that URL struct in url
variable. and also you can see that appendPathComponent
is mutating function. so you can apply modification on that mutable copy.
Upvotes: 1