Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//: 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

This comment has been minimized.

Copy link

bcapps commented May 23, 2016

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

This seems to work fine.

@sixten

This comment has been minimized.

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
You can’t perform that action at this time.