简体   繁体   中英

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

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

    }

// 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)!)
    }

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.

Swift4 You can also use :-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM