0

So I have this problem where I can't convert an element of my array to a string

I have a string like this

var description:[String] =["blue","yellow","red"]

and I want to give one element of my array to another variable which is chosen by another integer like this

var pick:[Int] = 2 var chosen:[String] = description[pick]

it says Cannot assign value of type 'String' to type '[String]' and to fix it xcode suggests to do it like this

var chosen:[String] = [description[pick]]

now if I want to cast this variable to another one or give it to a function or whatever it will say Cannot assign value of type 'String' to type '[[String]]' please help.

3
  • Is required for variable chosen to be an array? Otherwise you could just: var chosen: String = description[pick] Commented Jan 29, 2017 at 14:07
  • 1
    no you are right thanks. Commented Jan 29, 2017 at 14:14
  • I posted it as an answer, please mark it as Answered. Commented Jan 29, 2017 at 14:17

2 Answers 2

1

You are getting very confused here...

First...

var array = ["red", "yellow"]

Is an array of strings. Don't call it description. Call things what they are.

Second...

var pick: [Int]

Is declaring an array. Setting it = 2 doesn't make sense.

Change your last line to...

var chosen: String = array[pick]

In the above line using [String] here is telling the system that you are getting an array of Strings. You're not. You're getting a String here.

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

3 Comments

i was just making an example , like making a integer like carrot or etc but thanks i was just wrong with making chosen an array instead of string and mago helped me realize it thanks anyway.
@N9va ok. I still don't really know what you're trying to do. There are more problems with your code than just the string array.
well its in a class which is a object that has couple of traits and I choose between them and create different entities with int pick and int pick is random but it was not really necessary to type it all here so I just presented the bit that was confusing me.
0

Is required for variable chosen to be an array? Otherwise you could just:

var chosen: String = description[pick]

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.