arrays - What type should you use when you want to use index.advanceBy? -


i wanted find objects near object in array. thought write extension method this, error:

// error: cannot invoke 'advanceby' argument list of type '(int)' 

the int type wrong, indexof method takes self.distance argument , i'm not sure how use parameter type.

extension collectiontype generator.element : equatable {     func objectnear(object: self.generator.element, indexmodifier: int) -> self.generator.element? {         if let index = self.indexof(object) {             let newindex = index.advancedby(indexmodifier) // doesn't work             //let newindex = index.advancedby(1) // this works             if self.indices.contains(newindex) {                 return self[newindex]             }         }         return nil     } } 

(if there more swifty approach i'd happy hear it, i'd understand above in case.)

collectiontype has method

public func indexof(element: self.generator.element) -> self.index? 

and conforms to

public protocol indexable {     typealias index : forwardindextype     // ... } 

finally, forwardindextype has method

public func advancedby(n: self.distance) -> self 

therefore correct type index.distance:

func objectnear(object: self.generator.element, indexmodifier: index.distance) -> self.generator.element? { ... } 

but note advancing index beyond endindex can crash, e.g. character collections:

let c = "abc".characters print(c.objectnear("b", indexmodifier: 1)) // optional("c") print(c.objectnear("b", indexmodifier: 2)) // nil print(c.objectnear("b", indexmodifier: 3)) // fatal error: can not increment endindex 

a safe variant is:

func objectnear(object: generator.element, indexmodifier: index.distance) -> generator.element? {     if let index = indexof(object) {         if indexmodifier > 0 && index.distanceto(endindex) <= indexmodifier {             return nil         }         if indexmodifier < 0 && startindex.distanceto(index) < -indexmodifier {             return nil         }         return self[index.advancedby(indexmodifier)]     }     return nil } 

alternatively, if need method collections indexed int (such array) can define

extension collectiontype generator.element : equatable, index == int {      func objectnear(object: generator.element, indexmodifier: int) -> generator.element? {         if let index = self.indexof(object) {             let newindex = index + indexmodifier             if indices.contains(newindex) {                 return self[newindex]             }         }         return nil     } } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -