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

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?

1      

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... ;)

2      

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

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

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.