Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentsimmons/08e1e68a4defe2abca644d74106d1f31 to your computer and use it in GitHub Desktop.
Save brentsimmons/08e1e68a4defe2abca644d74106d1f31 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
protocol Message: class {
var uniqueID: String {get}
}
class LocalMessage: Message {
let uniqueID = NSUUID().UUIDString
}
var messages = [Message]()
let oneMessage = LocalMessage()
let secondMessage = LocalMessage()
messages += [oneMessage, secondMessage] as [Message] // The cast seems superfluous, but I can live with it.
// Scenario:
//
// A Message is updated via data from the web.
// I want to redisplay the corresponding row in a table view.
// To do so, I need the index of that row.
// I get the index of the row by getting the index of that Message in an array of Message.
//
// I don't actually care if the comparison uses pointer equality or ==. For my case it amounts to the same thing.
// These all fail to compile:
//let indexOfMessage = messages.indexOf(oneMessage) //cannot convert value of type 'LocalMessage' to expected argument type '@noescape (Message) throws -> Bool'
//
//let indexOfMessage = messages.indexOf(oneMessage as Message) //cannot convert value of type 'Message' to expected argument type '@noescape (Message) throws -> Bool'
//
//let indexOfMessage = (messages as NSArray).indexOfObjectIdenticalTo(oneMessage) //'[Message]' is not convertible to 'NSArray'
// I can make it work this way, using pointer equality (which is fine).
//
// Is there a better way to solve this problem, with performance that is not worse?
// (For instance, filter wouldn’t stop when it found the Message, but the for-loop does stop upon finding it.)
var indexOfMessage = 0
var found = false
for oneMessage in messages {
if oneMessage === oneMessage {
found = true
break
}
indexOfMessage++
}
if found {
print(indexOfMessage)
}
// Update — the answer comes via Twitter:
// https://twitter.com/bzamayo/status/734803341956485120
let indexOfMessage = messages.indexOf { $0 === oneMessage }
print(indexOfMessage)
@bcapps
Copy link

bcapps commented May 23, 2016

let index = messages.indexOf { message in
  return message === oneMessage
}

This seems to work fine.

@sixten
Copy link

sixten commented May 23, 2016

As an aside, if you need to loop over a sequence and also know the indices, enumerate() can help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment