0

I am new in swift and I am not able to get value for array my array is like this

(
    "http://ivs.upetch.com/tpaf/storage/uploads/banner/15762295031269.jpg",
    "http://ivs.upetch.com/tpaf/storage/uploads/banner/15762294973128.jpg",
    "http://ivs.upetch.com/tpaf/storage/uploads/banner/15762294928909.jpg"
)

My code is like this

    self.bannerarr = bannerdata as! NSArray
    print(self.bannerarr)

    for bannerurl in self.bannerarr{
    let stringbanner = self.bannerarr .object(at: bannerurl as! Int)
    print(stringbanner)
}

But when I am trying to get value from array it show me error as

Could not cast value of type '__NSCFString' (0x1084207a0) to 'NSNumber' (0x10493ed40).

Can someone please tell me what I am doing wrong

4
  • can you show the bannerurl Commented Dec 21, 2019 at 7:05
  • what the OP you expect Commented Dec 21, 2019 at 7:06
  • @Anbu.Karthik I am getting Url there ivs.upetch.com/tpaf/storage/uploads/banner/15762295031269.jpg Commented Dec 21, 2019 at 7:08
  • @Anbu.Karthik I need Index there Commented Dec 21, 2019 at 7:09

4 Answers 4

1

if you want the index for each element along with its value, you can use the enumerated() method to iterate over the array.

It returns a sequence of pairs (index, element), where index represents a consecutive integer starting at zero and element represents an element of the sequence.

  let bannerarr = ["http://ivs.upetch.com/tpaf/storage/uploads/banner/15762295031269.jpg",
    "http://ivs.upetch.com/tpaf/storage/uploads/banner/15762294973128.jpg",
    "http://ivs.upetch.com/tpaf/storage/uploads/banner/15762294928909.jpg"]

    // use your iteration as like
    for (index, element) in bannerarr.enumerated() {
      print("get Index \(index): getString \(element)")

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

Comments

0

// initialize data array and return it var data = String

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .SpellOutStyle

    for var i = 0; i < 3; i++ {
        let number = NSNumber.init(integer: i)
        data.append(formatter.stringFromNumber(number)!)
    }

Comments

0

Although the problem has been solved, but I want to tell you in your code the 'bannerurl' in the loop is the element. Maybe you should know that.

Comments

0

Swift4 You can also use :-

for i in 0..<self.bannerarr.count{
    print("\(i) \(self.bannerarr[i])")
}

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.