Search code examples
iosswiftfor-in-loop

how to use for in loop using NSNumber and Int in swift


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


Solution

  • 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)")
    
        }