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

SOLVED: day 12-optional chaining test q6 - code correct on test but error on Xcode

Forums > 100 Days of Swift

let shoppingList = ["eggs", "tomatoes", "grapes"]
let firstItem = shoppingList.first?.appending(" are on my shopping list") //error: Value of type 'String' has no member 'appending'

Hi, the code above is marked correct in test but does not work in XCode with error message.

//error: Value of type 'String' has no member 'appending'

I changed "appending" to "append". Still does not work.

Error: Cannot use mutating member on immutable value: 'first' is a get-only property

What changes should the code have to append the string to the array element?

3      

The code is correct.

Did you make sure to import Foundation at the beginning of your code? appending(_:) is a method provided by the Foundation framework. You will almost always need Foundation whenever you write Swift code.

Especially in a case like this. Swift's native String does not have a method called appending, but it is bridged with Foundation's NSString. And NSString does have an appending function: appending(_:) | Apple Developer Documentation

Without Foundation and NSString, you would need to do something like this:

let shoppingList = ["eggs", "tomatoes", "grapes"]
let firstItem = shoppingList.first! + " are on my shopping list"

But that doesn't demonstrate optioal chaining, so... ;)

4      

thanks @roosterboy. now it works with import Foundation. ok noted with thanks. I will import this framework with every swift code. :D

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.