WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Question: why name is a constant in my simple codes ?

Forums > 100 Days of SwiftUI

Hello this is a pretty simple example code in the Playground , but at the line of name = name.uppercased(), Xcode warns me that error: cannot assign to value: 'name' is a 'let' constant

How come name is a constant ? I didn't declare it as a constant or a variable.


import Cocoa

func isUppercase(_ name: String) -> String {
   name = name.uppercased()
}

let result = isUppercase("Mary")

print (result)

   

Parameters are passed into functions as constant (i.e., let) values.

Side note: It's a bad idea to name that function isUppercase. Names like is______ in Swift (and most languages) would be expected to return a boolean indicating whether or not the parameter is uppercased. If you want to convert a String to uppercase, name it something else, like uppercase or toUppercase.

1      

@roosterboy thank you as alway !

noted about the convention too.

Happy Lunar New Year and have a great year of tiger !

Boat

   

As @roosterboy say parameters passing in are none mutating however if you want them to be you need to add inout eg

func toUppercase(_ name: inout String) -> String {
   name.uppercased()
}

And when you call it you need a & in front of the variable that you want to mutate.

var mary = "Mary"
let result = toUppercase(&mary)
print(result) // MARY

More detail explanation What are inout parameters?

1      

@NigelGee thanks for the extensive explanation !

Will look into it !

have a great day,

Boat

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.