Last active
November 12, 2017 19:39
-
-
Save DominikBucher12/4acb550f22957f60dd301ccee6756d56 to your computer and use it in GitHub Desktop.
Swift Xcode extension snippet for getting array of strings from lines.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GetLinesStrings.swift | |
// | |
// Created by Dominik Bucher on 22/10/2017. | |
// Copyright © 2017 Dominik Bucher. All rights reserved. | |
// | |
/// This method should be universal and implemented right from Apple. | |
/// gets specified text from line indexes | |
/// | |
/// - Parameters: | |
/// - buffer: buffer to work with(usually the same instance as in all other functions) | |
/// - Returns: returns array of texts on specific lines | |
class func getSelectedLinesText(withBuffer buffer: XCSourceTextBuffer) throws -> [String]{ | |
guard let selectedRange = buffer.selections as? [XCSourceTextRange], | |
let firstRange = selectedRange.first | |
else { throw NSError() } // You can handle the completion handler here, something like no selection or something like that... | |
let indexes = Array(firstRange.start.line...firstRange.end.line) | |
return indexes.map({ buffer.lines[$0] as? String }).flatMap({$0}) | |
} | |
// MARK: - Usage: | |
class SourceEditorCommand: NSObject, XCSourceEditorCommand { | |
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { | |
do { | |
let selectedLines = try getSelectedLinesText(withBuffer: invocation.buffer) | |
// Prints array of selected lines, not limited by UTI or anything... Cool thing about the Xcode extensions is | |
// that you can use them in any other language like Python or Ruby 👌🏻. | |
// Print isn't handled in Xcode extensions too well, | |
// see this: https://stackoverflow.com/questions/41948124/print-not-working-in-swift-3-extensions | |
// for further disambiguation. | |
print(selectedLines) | |
} | |
catch let err { completionHandler(err) } | |
completionHandler(nil) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe it would be nice to add this as extension to XCSourceEditorCommand protocol to have it straight build-in and ready to go... But I don't really like real implementations in protocol extensions... So I will think about another idea...