1

On the last line it gives the error " Cannot assign value of type '[String]' to type 'String' ", im a beginner to Swift and i have tried lot things but cant solve this issue

func shortNameFromName (_ fullName: String) -> String{
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName
}

3 Answers 3

2

Your function is trying to return a String yet the value you are actually trying to return is a [String]

Simply change it to this:

func shortNameFromName (_ fullName: String) -> [String] {
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName
}

Alternatively if you do just want to return a single string value then do this to return the first object from the array of strings (or whichever string you want to return)

func shortNameFromName (_ fullName: String) -> String{
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName[0]
}

The [0] denotes which string you want to return from the array by it's index

Sign up to request clarification or add additional context in comments.

Comments

1

The method components(separatedBy:) returns a string array [String].

You function's return type is String and not [String]

So there are 2 ways to resolve the issue depending on your requirement.

1. Use [String] as return type of function, i.e.

func shortNameFromName (_ fullName: String) -> [String]
{
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName
}

2. Return a particular value from shortName array, i.e.

func shortNameFromName (_ fullName: String) -> String
{
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName.first! //Make sure shortName is not empty before force unwrapping it
}

Comments

0

Quoting from Apple Docs:

components(separatedBy:)

Returns an array containing substrings from the receiver that have been divided by a given separator.

Decalaration:

func components(separatedBy separator: String) -> [String]

So your function should be like this:

func shortNameFromName (_ fullName: String) -> [String] {
    var lowerCasedName = fullName.lowercased()
    var shortName = lowerCasedName.components(separatedBy: " ")
    return shortName
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.