UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

Forums > 100 Days of SwiftUI

@boat  

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)

2      

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.

3      

@boat  

@roosterboy thank you as alway !

noted about the convention too.

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

Boat

2      

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?

3      

@boat  

@NigelGee thanks for the extensive explanation !

Will look into it !

have a great day,

Boat

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.