BLACK FRIDAY: 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

@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      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.