0

I have a table view in which i want to put row names from my array's object.

I have declared an array

var myArray = [1,2,3,4,5,6,7]

in my tableView how can I put value from this array.I didn't find ObjectAtIndex method, so I am doing this

myLabel.text= String(format: "%@",array [ indexPath.row])
2
  • let myArray = [1,2,3,4,5,6,7]; let text = "\(myArray[indexPath.row])". You should read The Swift Programming Guide: Strings and Characters, which covers String Interpolation. Commented Jul 10, 2015 at 11:23
  • when I can use let and var in case of Array? should I use let for NSArray and var for NSMutableArray? Commented Jul 10, 2015 at 11:32

5 Answers 5

1

You can do it in this way.

myLabel.text= String(stringInterpolationSegment: myArray[indexPath.row]!)
Sign up to request clarification or add additional context in comments.

2 Comments

yes both way are correct . but can you tell me difference between both methods?
with "\ (yourValue)" usage you can cast your any value to string but if it is complex variables, appending or dynamically created , it is better using stringInterpolationSegment method
1

The easiest way is using string interpolation:

myLabel.text = "\(array[indexPath.row])"

If you want to know more, consult the official documentation

2 Comments

Its working for me. Is ObjectAtIndex removed in Swift?
objectAtIndex is a method of NSArray, in swift that's been replaced by the subscript operator []. However the swift array and NSString are compatible and interchangeable, you can just cast an array into NSString to have access to all its properties and methods: let nsArray = array as NSArray
1

Your myArray is swift Array of type [Int] and it is not NSArray, swift array doesn't have property ObjectAtIndex so you can access element from swift array with index this way:

var myArray = [1,2,3,4,5,6,7]
myLabel.text = "\(myArray[indexPath.row])"

And myArray[indexPath.row] will return Int because myArray type is [Int].

If you want to assign text to myLabel then you have to convert that to String from Int and you can do that by string interpolation.

Comments

1

You have two mistakes there. First you have declared myArray not array. Second when using integers you have to use %d. Try like this:

let myArray = [1,2,3,4,5,6,7]

myLabel.text = String(format: "%d", myArray[indexPath.row])

Comments

0

You can write like this also:

myLabel.text = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.