Create a gist now

Instantly share code, notes, and snippets.

@erica /after.swift
Last active Jun 21, 2016

import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: (NSError?) -> Void ) -> Void {
var updatedSelections: [XCSourceTextRange] = []
let literalMapping = [
"NSColor(": "#colorLiteral(",
"NSImage(named:": "#imageLiteral(resourceName:"
]
for (lineIndex, line) in invocation.buffer.lines.enumerated() {
guard let line = line as? String else { continue }
let newLine = literalMapping.reduce(line) {
(line: String, kv: (key: String, value: String)) -> String in
return line.replacingOccurrences(of: kv.key, with: kv.value)
}
if line != newLine {
invocation.buffer.lines[lineIndex] = newLine
updatedSelections.append(
{
$0.start = XCSourceTextPosition(line: lineIndex, column: 0)
$0.end = XCSourceTextPosition(line: lineIndex + 1, column: 0)
return $0
}(XCSourceTextRange()))
}
}
invocation.buffer.selections.setArray(updatedSelections)
completionHandler(nil)
}
}
import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: (NSError?) -> Void ) -> Void {
var updatedLineIndexes = [Int]()
for lineIndex in 0 ..< invocation.buffer.lines.count {
let originalLine = invocation.buffer.lines[lineIndex] as! String
let literalMapping = ["UIColor(": "#colorLiteral(",
"UIImage(named:": "#imageLiteral(resourceName:"]
var newLine = originalLine
for (old, new) in literalMapping {
newLine = newLine.replacingOccurences(of: old, with: new)
}
if originalLine != newLine {
updatedLineIndexes.append(lineIndex)
invocation.buffer.lines[lineIndex] = newLine
}
}
// Select all lines that received replacements
let updatedSelections: [XCSourceTextRange] = updatedLineIndexes.map { lineIndex in
let lineSelection = XCSourceTextRange()
lineSelection.start = XCSourceTextPosition(line: lineIndex, column: 0)
lineSelection.end = XCSourceTextPosition(line: lineIndex + 1, column: 0)
return lineSelection
}
invocation.buffer.selections.setArray(updatedSelections)
// Finish the command
completionHandler(nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment