• Stars
    star
    531
  • Rank 80,538 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fast and powerful Swift string scanning made simple

Sweep

Swift Package Manager Mac + Linux Twitter: @johnsundell

Welcome to Sweep — a powerful and fast, yet easy to use, Swift string scanning library. Scan any string for substrings appearing between two sets of characters — for example to parse out identifiers or metadata from a string of user-defined text.

Sweep can be dropped into a project as a general-purpose string scanning algorithm, or act as the base for custom, more high-level scanning implementations. It aims to complement the Swift standard library’s built-in string handling APIs, both in terms of its design, and also how its implemented in an efficient way in line with Swift’s various string conventions.

Examples

The easiest way to start using Sweep is to call the substrings method that it adds on top of StringProtocol — meaning that you can use it on both “normal” strings and Substring values.

Here’s an example in which we scan a string for HTML tags, and both identify the names of all tags that appear in the string, and also any text that should be rendered in bold:

import Sweep

let html = "<p>Hello, <b>this is bold</b>, right?</p>"
let tags = html.substrings(between: "<", and: ">")
print(tags) // ["p", "b", "/b", "/p"]

let boldText = html.substrings(between: "<b>", and: "</b>")
print(boldText) // ["this is bold"]

Sweep can also scan for different patterns, such as a prefix appearing at the start of the scanned string, or its end. Here we’re using those capabilities to identify headings in a string of Markdown-formatted text:

import Sweep

let markdown = """
## Section 1

Text

## Section 2
"""

let headings = markdown.substrings(between: [.prefix("## "), "\n## "],
                                   and: [.end, "\n"])

print(headings) // ["Section 1", "Section 2"]

Since Sweep was designed to fit right in alongside Swift’s built-in string APIs, it lets us compose more powerful string scanning algorithms using both built-in functionality and the APIs that Sweep adds — such as here where we’re parsing out an array of tags from a string written using a custom syntax:

import Sweep

let text = "{{tags: swift, programming, xcode}}"
let tagStrings = text.substrings(between: "{{tags: ", and: "}}")
let tags = tagStrings.flatMap { $0.components(separatedBy: ", ") }
print(tags) // ["swift", "programming", "xcode"]

Sweep was also designed to be highly efficient, and only makes a single pass through each string that it scans — regardless of how many different patterns you wish to scan for. In this example, we’re using two custom matchers to parse two pieces of metadata from a string:

import Sweep

let text = """
url: https://swiftbysundell.com
title: Swift by Sundell
"""

var urls = [URL]()
var titles = [String]()

text.scan(using: [
    Matcher(identifiers: ["url: "], terminators: ["\n", .end]) { match, range in
        let string = String(match)
        let url = URL(string: string)
        url.flatMap { urls.append($0) }
    },
    Matcher(identifiers: ["title: "], terminators: ["\n", .end]) { match, range in
        let string = String(match)
        titles.append(string)
    }
])

print(urls) // [https://swiftbysundell.com]
print(titles) // ["Swift by Sundell"]

Sweep is not only efficient in terms of complexity, it also has a very low memory overhead, thanks to it being built according to Swift’s modern string conventions — making full use of types like Substring and String.Index, and avoiding unnecessary copying and mutations when performing its scanning.

Installation

Sweep is distributed as a Swift package, and it’s recommended to install it using the Swift Package Manager, by declaring it as a dependency in your project’s Package.swift file:

.package(url: "https://github.com/JohnSundell/Sweep", from: "0.1.0")

For more information, please see the Swift Package Manager documentation.

Contributions & support

Sweep is developed completely in the open, and your contributions are more than welcome.

Before you start using Sweep in any of your projects, it’s highly recommended that you spend a few minutes familiarizing yourself with its documentation and internal implementation (it all fits in a single file!), so that you’ll be ready to tackle any issues or edge cases that you might encounter.

To learn more about the principles used to implement Sweep, check out “String parsing in Swift” on Swift by Sundell.

Sweep does not come with GitHub Issues-based support, and users are instead encouraged to become active participants in its continued development — by fixing any bugs that they encounter, or improving the documentation wherever it’s found to be lacking.

If you wish to make a change, open a Pull Request — even if it just contains a draft of the changes you’re planning, or a test that reproduces an issue — and we can discuss it further from there.

Hope you enjoy using Sweep! 😀

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,763
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Ink

A fast and flexible Markdown parser written in Swift.
Swift
2,336
star
5

Unbox

[Deprecated] The easy to use Swift JSON decoder
Swift
1,956
star
6

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,946
star
7

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts 🏃
Swift
1,869
star
8

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use 🚀
Swift
1,818
star
9

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
10

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,735
star
11

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
12

Codextended

Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️
Swift
1,488
star
13

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
14

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
15

CollectionConcurrencyKit

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.
Swift
730
star
16

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
17

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
18

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
19

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
377
star
20

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
339
star
21

Identity

🆔 Type-safe identifiers in Swift
Swift
298
star
22

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
23

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
24

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
25

Flow

Operation Oriented Programming in Swift
Swift
217
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
183
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star
51

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star