Swift: cannot subscript a value of type aka 'Array<Character>'

I'm trying to access to one character in string but I'm getting the following error:

error: cannot subscript a value of type 'Array<_Element>' (aka 'Array<Character>')
        finalString = characters [ 5 ]

Here is my code:

// my string:

var str = "Hello, playground"

// I'm converting the string into array of characters:

let characters = Array(str.characters)

// String where I want to transfer the character:

var finalString:String

finalString = characters [ 5 ]

But in the last line of code is where I get the error. Any of you knows what I'm doing wrong or a way around this error.

I'll really appreciate your help

Answers


You have an array of Characters, you need to turn that back into a string to get what you want. Try this:

// my string:
var str = "Hello, playground"

// I'm converting the string into array of characters:
let characters = Array(str.characters)

// String where I want to transfer the character:
var finalString = String(characters[ 5 ])

Need Your Help

When using a unique alphanumeric string for a short url, is it better to store the created string in the database or encode/decode on the fly?

php url base64 short short-url

I want to create shortened links for specific pieces of content on my site. To view these pages now, I pull the relevant content via the content ID passed via GET (ie, mysite.com/content/?id=332). To