senty senty - 7 months ago 24
Swift Question

Check if index exists for Array of NSURL

I have an array of NSURL with 3 elements. I am modifying and reseting(making nil) the elements, so I need to check if the element with the index exists. Otherwise, I receive array out of index. My problem is that as this array is array of NSURLs, I can't use many functions.

data[0][0]
,
data[0][1]
,
data[0][3]



  • So using
    self.data[0][2].absoluteString
    would crash.

  • I can't use
    indices.contains(index)
    to check



What is the way of checking if the array element of
NSURL
with index path exists?

I want to do..

if (data[0][0] exists) {
// do
}

Answer

You can find it through count

var data = [[String]]()

let data1 = ["test 1","test 2"]
data.append(data1)

let indexToFind = 1

if data[0].count > indexToFind {
    print("found")
    print("value \(data[0][indexToFind])")
}
else {
    print("not found")
}

If indexToFind = 2 then you will get

not found

If indexToFind = 1 then you will get

found

value test 2


FOR URL

You can count characters in url by absoluteString.characters.count

var data = [[NSURL?]]()

let data1 = [NSURL(string: ""),NSURL(string: ""),NSURL(string:"http://google.com")]
data.append(data1)

let indexToFind = 2

if data[0].count > indexToFind {
    print("found")
    print("value \(data[0][indexToFind]!)")

    if data[0][indexToFind]!.absoluteString.characters.count > 0 {
        print("this is an url")
    }
}
else {
    print("not found")
}

OUTPUT :

found

value http://google.com

this is an url

Comments