Sugar is a sweetener for your Cocoa implementations.

Overview

Sugar

Sugar is a sweetener for your Cocoa implementations.

CI Status Version Carthage Compatible License Platform Swift

Table of Contents

Hue Icon

iOS

Application

let appName = Application.name             // CFBundleDisplayName : String
let appVersion = Application.version       // CFBundleShortVersionString : String
let appExecutable = Application.executable // CFBundleExecutable : String
let appBundle = Application.bundle         // CFBundleIdentifier : String
let appSchemes = Application.schemes       // CFBundleURLSchemes : [String]
let mainAppScheme = Application.mainScheme // CFBundleURLSchemes.first : String?

Gain easy access to main bundle information.

Screen

let pixelSize = Screen.pixelSize // CGSize(width: screenWidth * scale, height: screenHeight * scale)

Get the actual pixel information of the device screen.

Simulator

if !Simulator.isRunning {
  // add device specific operations here
}

To easily exclude operations from when you as a developer runs the application in the simulator, not subscribing to push notification or running analytics operations etc.

Keyboard Observer

Observe keyboard showing and hiding events, and handle it

let handler = BasicKeyboardHandler()
handler.show = { [weak self] height in
  // move text fields up
}

handler.hide = { [weak self] in
  // move text fields back to original position
}

keyboardObserver = KeyboardObserver(handler: handler)

Currently support

  • BasicKeyboardHandler: basic UIView animation
  • InsetKeyboardHandler: animate UIScrollView insets
  • ConstraintKeyboardHandler: animate bottom layout constraint
  • CustomKeyboardHandler: custom handling

iOS Extensions

UIView

.optimize()
let view = UIView.optimize
/*
  clipsToBounds = true
  layer.drawsAsynchronously = true
  opaque = true
*/

UIImage

+Rendering mode
image.original // imageWithRenderingMode(.AlwaysOriginal)
image.template // imageWithRenderingMode(.AlwaysTemplate)

Shared

SequenceType

let first: Int? = items.findFirst({ $0 > 10 })

Dates

Compare

if date1 < date2 {
  // do something
} else if date1 >= date2 {
  // do something else
}

Construct

let _ = 5.day
let _ = 3.week

Frame

let view = UIView()
view.width = 200
view.height = 200
view.x = 25
view.y = 25

print(view.width) // prints 200
print(view.height) // prints 200
print(view.x) // prints 25
print(view.y) // prints 25

Grand Central Dispatch

dispatch {
  // dispatch in main queue
}

dispatch(queue: .Background) {
  // dispatch in background queue
}

lazy var serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL)
dispatch(queue: .Custom(serialQueue)) {
  // dispatch in a serial queue
}

Easy dispatching with grand central dispatch. Support all the regular global queues: Main, Interactive, Initiated, Utility, Background. And .Custom() for your own dispatch queues.

Localization

let string = localizedString("My Profile")
let formattedString = localizedString(key: "%d numbers", arguments: 10)

Swift access (pun intended) to NSLocalizedString, you will get more valid auto completion with this one, we promise.

Once

let once = Once()
once.run {
  // do something
}

once.run {
  // no effect
}

Operators

var url = NSURL(string: "hyper.no")!
url ?= NSURL(string: "\\/http")
// url is equal to hyper.no

The ?= only assigns values if the right is not nil.

Range

let acceptable = 200..<300
if acceptable.contains(response.statusCode) {
  // Status code is between 200 and 299.
}

Regex

if "[email protected]".isEmail() {
  // Is email
}

let stringNumber = "1984"
if stringNumber.isNumber() {
  // Is a number
}

if stringNumber.matches("^[0-9]+$") {
  // Is a number
}

Shared Extensions

+Queueable

struct Object: Queueable {

  func process() -> Bool { return true }
}

let myQueue = [Object(), Object()]
myQueue.processQueue()

Make your own processing queue with ease, just make your object conform the Queueable.

public protocol Queueable {
  func process() -> Bool
}

URLStringConvertible

let urlString = "https://hyper.no"
let url = urlString.url

Highly inspired by / borrowed from Alamofire's implementation of URLStringConvertible.

Core Foundation

let string = "hyper/oslo"
string.length // 10
string.truncate(5) // hyper...
string.split(/) // ["hyper", oslo]

if string.isPresent {
  // do something
}

if string.contains("hyper") {
  // found hyper
}

var dirtyString = "   hyper   "
print(dirtyString.trim()) // prints "hyper"

Just some extra sugar on top of String for getting the length, truncating, trimming or splitting a String.

isPresent is the opposite of isEmpty.

contains and be used to check if a string contains a word or pharse.

Swizzler

Bool { return true } func swizzled_method() -> Bool { return false } } let object = Swizzled() object.method() // false ">
class Swizzled: NSObject {

  override class func initialize() {
    struct Static {
      static var token: dispatch_once_t = 0
    }

    if self !== Swizzled.self {
    return
  }

  dispatch_once(&Static.token) {
    Swizzler.swizzle("method", cls: self)
  }
}

  dynamic func method() -> Bool {
    return true
  }

  func swizzled_method() -> Bool {
    return false
  }
}

let object = Swizzled()
object.method() // false

Everyday we are swizzling, this use to be mundane, now it just Swiftling, we mean, super fast.

Then

let UIView().then {
  $0.backgroundColor = UIColor.blackColor()
}

This implementation is brought to you by @devxoul by his awesome Then repository.

Type Alias

public typealias JSONArray = [[String : AnyObject]]
public typealias JSONDictionary = [String : AnyObject]

UITesting

if UITesting.isRunning {
  // tests are running
} else {
  // everything is fine, move along
}

To easily include or exclude operations for when you are running UI tests.

UnitTesting

if UnitTesting.isRunning {
  // running test
}

func testPerformance() {
  let measurement = measure {
    // run operation
  }
}

Check if you are running UniTests and to measure performance.

Installation

Sugar is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Sugar'

Sugar is also available through Carthage. To install just write into your Cartfile:

github "hyperoslo/Sugar"

Sugar is also available through Swift Package Manager.

.package(url: "https://github.com/hyperoslo/Sugar.git", .upToNextMajor(from: "5.0.1")),

Author

Hyper Interaktiv AS, [email protected]

License

Sugar is available under the MIT license. See the LICENSE file for more info.

Comments
  • Handling gesture the easy way

    Handling gesture the easy way

    This make handling gesture more easily, with block

    It works this way

    • ViewController -strong-> GestureSense -strong-> Target -strong-> handler block
    • UIGestureRecognizer -weak-> Target
    • It won't attach the same kind of gesture twice
    let sense = GestureSense()
    let view = UIView()
    
    sense.tap(view) { gr in
    
    }
    
    sense.pan(view) { gr in
    
    }
    
    sense.pan(view) { gr in
    
    }
    
    opened by onmyway133 12
  • Adress the elephant in the room, is Sugar starting to get obese ?

    Adress the elephant in the room, is Sugar starting to get obese ?

    As @vadymmarkov brought up in (https://github.com/hyperoslo/Sugar/pull/78#issuecomment-220854098), Sugar is growing out of proportion, one can even start to call it obese.

    We need to come up with a good strategy to tackle this problem. As I wrote in #78;

    I think we need to adress this is a good way, maybe splitting it out in to separate repos where it makes sense and then starting to mark things as deprecated and then remove extract and remove bits and pieces from the Sugar core.

    That could be one way of handling it. But we need to find a good middle ground to find what goes into Sugar and what does not. Do we see Sugar as a incubator for future pods, exposing where there could be potential for more components or is it more like the name implies, a syntax sugar for Cocoa and Cocoa Touch were we feel that Apple default implementation is falling short.

    Regardless of that, the issue needs solving so, without further ado, discuss peoples!

    post-62208-silicon-valley-erlich-gilfoyle-fx3n

    opened by zenangst 7
  • Feature/split string extension

    Feature/split string extension

    With this PR, you can easily split up String’s into multiple parts by calling split().

    "root/path/file".split("/")
    // ["root", "path", "file"]
    
    opened by zenangst 7
  • Contains method in Range

    Contains method in Range

    I was doing some Networking and wanted to check if the status code was in a range, did this tiny thing. You call it like this:

    let OK = 200..<300
    OK.contains(response.statusCode)
    

    @hyperoslo/malibu

    opened by RamonGilabert 6
  • Add support for all global queues

    Add support for all global queues

    This PR adds some functionality to dispatch. Now you can select between all global queues by just passing an enum value;

    It still defaults to .Main so the public API does not change.

    # Main queue
    dispatch {}
    
    # Interactive
    dispatch(queue: .Interactive) {}
    
    # Interactive
    dispatch(queue: .Initiated) {}
    
    # Interactive
    dispatch(queue: .Utility) {}
    
    # Background
    dispatch(queue: .Background) {}
    

    You can still add your own custom queue by doing this;

    # Custom
    dispatch(queue: .Custom(myQueue)) {}
    
    opened by zenangst 6
  • Please create a 2.3 branch.

    Please create a 2.3 branch.

    The only change required to support swift 2.3 is self.init(CGImage: image!.CGImage!) in the branch instead of self.init(CGImage: image.CGImage!) in the file UIImage+Extensions.swift

    opened by navisingh 5
  • Add KeyboardObserver and Handler to handle keyboard events

    Add KeyboardObserver and Handler to handle keyboard events

    • Observer keyboard will show and will hide events
    • Currently support handler for basic animation, custom block, scrollview insets, layout constraint
    • Add new handler by conforming to KeyboardHandler protocol
    opened by onmyway133 5
  • Can release a tagged version for Swift 3?

    Can release a tagged version for Swift 3?

    I'm working with CocoaPods package in there isn't possible point to a branch, is there possible release a tagged version of Sugar package to Swift 3 users?

    opened by RafaelPlantard 4
  • Add/isPresent on String

    Add/isPresent on String

    This is the reverse of isEmpty but it will help improve the implementation in your application.

    So instead of:

    if !value.isEmpty {}
    

    You could do:

    if value.isPresent {}
    
    opened by zenangst 3
  • Upgrade project to swift 4.2

    Upgrade project to swift 4.2

    I have made all the necessary changes to upgrade this project to swift version 4.2. This included all API changes in actual application code as well as test code. The projects produces no warnings.

    Further discussion: Sugar currently offers the computed property .length on the String type. This was added to avoid typing .character.count everytime someone wanted to access the character count of a string. Since the original implementation of Sugar, Swift has since reverted back to using .count on the string type directly which renders this property meaningless. I did not want to remove it to avoid breaking existing code, but I would like to propose removing this completely.

    opened by technocidal 2
  • Swift 3 Date is comparable. These operators will conflict with Swift 3 operators.

    Swift 3 Date is comparable. These operators will conflict with Swift 3 operators.

    If you use current Sugar with Swift 3 environment and use >, <, >=, <= operators, it will lead to compile error like follows.

    Ambiguous use of operator '<'
    

    We shouldn't have these operators in Sugar anymore.

    opened by yfujiki 2
Releases(5.0.1)
Owner
HyperRedink
Connected creativity
HyperRedink
Swift implementations for function currying

Curry Swift implementations for function currying. For more info on function currying in Swift, please refer to this blog post Version Compatibility N

thoughtbot, inc. 487 Oct 25, 2022
Approximate is a Swift package that provides implementations of floating point comparisons for the Swift ecosystem

Approximate Approximate floating point equality comparisons for the Swift Programming Language. Introduction Approximate is a Swift package that provi

Christopher Blanchard 1 Jun 1, 2022
📦 KeyPath dynamicMemberLookup based syntax sugar for Swift.

DuctTape ?? KeyPath dynamicMemberLookup based syntax sugar for Swift. let label: UILabel = UILabel().ductTape .numberOfLines(0) .textColor(.re

Taiki Suzuki 171 Nov 4, 2022
✨ Super sweet syntactic sugar for Swift initializers

Then ✨ Super sweet syntactic sugar for Swift initializers. At a Glance Initialize UILabel then set its properties. let label = UILabel().then { $0.t

Suyeol Jeon 4k Jan 4, 2023
SharkUtils is a collection of Swift extensions, handy methods and syntactical sugar that we use within our iOS projects at Gymshark.

SharkUtils is a collection of Swift extensions, handy methods and syntactical sugar that we use within our iOS projects at Gymshark.

Gymshark 1 Jul 6, 2021
🍯 Syntactic sugar for Moya

MoyaSugar Syntactic sugar for Moya. Why? Moya is an elegant network abstraction layer which abstracts API endpoints gracefully with enum. However, it

Suyeol Jeon 186 Jan 6, 2023
Synatax sugar for Measurement of Foundation.

WrappedMeasurement 2022 © Weizhong Yang a.k.a zonble Syntax sugar for NSMeasurement of Foundation. NSMeasurement and NSUnit compose a great tool to le

Weizhong Yang a.k.a zonble 8 Jan 25, 2022
HumanMeasurementSwift - Synatax sugar for Measurement of Foundation

HumanMeasurement 2022 © Weizhong Yang a.k.a zonble Syntax sugar for NSMeasuremen

Weizhong Yang a.k.a zonble 8 Jan 25, 2022
And - Syntactic sugar for Swift initializers

And Syntactic sugar for Swift initializers Usage let label = UILabel().and { $0

donggyu 4 Jun 10, 2022
A Cocoa library to extend the Objective-C programming language.

The Extended Objective-C library extends the dynamism of the Objective-C programming language to support additional patterns present in other programm

Justin Spahr-Summers 4.5k Dec 30, 2022
Automatically set your keyboard's backlight based on your Mac's ambient light sensor.

QMK Ambient Backlight Automatically set your keyboard's backlight based on your Mac's ambient light sensor. Compatibility macOS Big Sur or later, a Ma

Karl Shea 29 Aug 6, 2022
LibAuthentication will simplify your code when if you want to use FaceID/TouchID in your tweaks.

LibAuthentication will simplify your code when if you want to use FaceID/TouchID in your tweaks.

Maximehip 6 Oct 3, 2022
RNH Tracker is a GPS logger for iOS (iPhone, iPad, iPod) Track your location and send your logs to RNH Regatta :-)

RNH Tracker for iOS + WatchOS RNH Tracker is a GPS logger for iOS (iPhone, iPad, iPod) with offline map cache support. Track your location, add waypoi

Ed Cafferata 0 Jan 23, 2022
Record your position and export your trip in GPX with GPS Stone on iOS.

GPS Stone Register your trips and export them as GPX files. Notes We currently have included a UIRequiredDeviceCapabilities with a location-services v

Frost Land 11 Sep 24, 2022
Add “Launch at Login” functionality to your macOS app in seconds

LaunchAtLogin Add “Launch at Login” functionality to your macOS app in seconds It's usually quite a convoluted and error-prone process to add this. No

Sindre Sorhus 1.3k Jan 6, 2023
LifetimeTracker can surface retain cycle / memory issues right as you develop your application

LifetimeTracker Bar style Circular style LifetimeTracker can surface retain cycle / memory issues right as you develop your application, and it will s

Krzysztof Zabłocki 2.8k Jan 4, 2023
The simplest way to display the librarie's licences used in your application.

Features • Usage • Translation • Customisation • Installation • License Display a screen with all licences used in your application can be painful to

Florian Gabach 51 Feb 28, 2022
Generate a privacy policy for your iOS app

PrivacyFlash Pro To easily run PrivacyFlash Pro get the latest packaged release. Learn more about PrivacyFlash Pro in our research paper. PrivacyFlash

privacy-tech-lab 141 Dec 22, 2022
A handy collection of more than 500 native Swift extensions to boost your productivity.

SwifterSwift is a collection of over 500 native Swift extensions, with handy methods, syntactic sugar, and performance improvements for wide range of

SwifterSwift 12k Jan 7, 2023