Code Monkey home page Code Monkey logo

ezswiftextensions's Introduction

EZSwiftExtensions

Carthage compatible CocoaPods Compatible
License Platform Language Language Language

Build Status codecov.io MIT

How Swift standard types and classes were supposed to work. A collection of useful extensions for the Swift Standard Library, Foundation, and UIKit.

Join our online chat at Gitter

Example Usage

Easily get an object at a specified index:

var myArray = ["charmander","bulbasaur","squirtle"]
print(myArray.get(1)) // "bulbasaur"

Easily access a random element:

var myArray = ["charmander","bulbasaur","squirtle"]
print(myArray.random()) // bulbasaur or something else

Easily find the indexes of an object:

var myArray = ["charmander","bulbasaur","squirtle","charmander"]
print(myArray.indexesOf("charmander")) // [0,3]

Easily check if an array contains another array:

var myArray = ["charmander","bulbasaur","squirtle"]
print(myArray.containsArray(["charmander","bulbasaur"])) // true
print(myArray.containsArray(["string"])) // false

Block Objects These objects use completion blocks instead of selectors, taken from: CEMKit-Swift Easily initialize a BlockButton:

let button = BlockButton(x: 0, y: 0, w: 100, h: 100) { (sender) -> Void in
    print("Block button clicked!")
}
let button1 = BlockButton(x: 0, y: 0, w: 100, h: 100)
button1.addAction { (sender) -> Void in
    print("Block button clicked!")
}

// There are also BlockWebView, BlockTap, BlockPan, BlockSwipe, BlockPinch, BlockLongPress

Easily convert between different types:

var myCGFloat = myInt.toCGFloat
var myString = myInt.toString
var myDouble = myString.toDouble
var myInt = myDouble.toInt

Easily toggle it:

var myBool: Bool = true
print(myBool.toggle()) // false

Easily initialize your objects:

let myView = UIView(x: 0, y: 0, w: 100, h: 100)
print(myView.frame) // (0.0, 0.0, 100.0, 100.0)

Easily access your ViewController on top of your view stack:

ez.topMostViewController?.presentViewController(myAlertController, animated: true, completion: nil)
// topMostViewController is your rootViewController
// Intended for showing small VCs like UIAlertControllerstring.length, string.capitalizefirst, string.trim, string.isemail, 

Easily initialize your colors:

let myColor = UIColor(r: 100, g: 100, b: 100) // Default alpha is 1

Easily run block of codes after a certain delay:

Timer.runThisAfterDelay(seconds: 2) { () -> () in
    print("Prints this 2 seconds later in main queue")
}

Easily run code every seconds:

var count = 0
Timer.runThisEvery(seconds: 1) { (timer) -> Void in
    print("Will print every second")
    if count == 3 {
        timer?.invalidate()
    }
    count += 1
}

Easily access your projects version and build numbers:

print(ez.appVersion) // 0.3
print(ez.appBuild) // 7
print(ez.appVersionAndBuild) // v0.3(7)

Easily track screen shots:
ez.detectScreenShot { () -> () in
    print("User took a screen shot")
}

Installation

Manually (~10 seconds)

  1. Download and drop '/Sources' in your project.
  2. Congratulations!

Install via CocoaPods (~10 seconds)

You can use CocoaPods to install EZSwiftExtensions by adding it to your Podfile:

platform :ios, '8.0'
use_frameworks!
pod 'EZSwiftExtensions' #Stable release for Swift 3.0

pod 'EZSwiftExtensions', :git => 'https://github.com/goktugyil/EZSwiftExtensions.git' #Latest release for Swift 3.0
pod 'EZSwiftExtensions', :git => 'https://github.com/goktugyil/EZSwiftExtensions.git', :branch => 'Swift2.3' #For Swift 2.3
pod 'EZSwiftExtensions', '~> 1.6' #For Swift 2.2

To get the full benefits import EZSwiftExtensions wherever you import UIKit

import UIKit
import EZSwiftExtensions

Install via Carthage

Create a Cartfile that lists the framework and run carthage bootstrap. Follow the instructions to add $(SRCROOT)/Carthage/Build/iOS/EZSwiftExtensions.framework to an iOS project.

github "goktugyil/EZSwiftExtensions"

Requirements

  • Swift 2 or later

Possible features

  • More extensions! Please if there is an extension you are constantly using, send a pull request now!
  • Fancy pictures and jpgs in documentation.
  • Documentations inside code
  • List of contents inside readme
  • Completing TODOs in source code.
  • OSX compatibility and add here https://github.com/AndrewSB/awesome-osx

Sources Used

And countless gists and stackoverflow answers.

License

EZSwiftExtensions is available under the MIT license. See the LICENSE file.

Keywords

swift, extension, uikit, exswift, foundation, library, framework, tool

ezswiftextensions's People

Contributors

alkalin3 avatar bcylin avatar broccolii avatar bryant1410 avatar daniel-lopez avatar demiculus avatar dendim0n avatar dfrib avatar diogot avatar esqarrouth avatar furuyan avatar gramireza avatar inket avatar jaja-digitalspaceexplorer avatar khalian avatar kusakusakusa avatar lfarah avatar nataliachodelski avatar piv199 avatar pnishanth avatar rahimkhalid avatar readmecritic avatar rugheid avatar sagarmusale8 avatar thellimist avatar valeit avatar vayyala avatar vilapuigvila avatar vinayjn avatar yu-w avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ezswiftextensions's Issues

Switch Extensions

I'd like the UISwitch to have a .toggle() just like Booleans have a .toggle(), so:

var myBool: Bool = true // True
myBool.toggle() // False
var mySwitch: UISwitch = UISwitch(x: 0, y: 0, w: 50, h: 50)
mySwitch.setOn(true, animated: true) // True
mySwitch.toggle() //False

Stop adding new features, start adding more tests!

This is our test coverage at the moment. Test Coverage

At this point, stability and optimization is more important than new features. So if you want to contribute:

  • Copy the real life scenarios in readme.md into unit tests or vice versa (Very easy and beginner friendly)
  • Add new tests to uncovered methods
  • Optimize speed/syntax/document/version compatibility of current methods

I will be creating empty test files for everything so it will be easy to fill in. Ideally if a user wants to know what a function does, they should be able to just check the tests files and understand from the example code in there.

Thank you all for contributing!

Should extension methods have prefix, like ezs_?

Thank you for the useful extensions!

We recently integrated EZSwiftExtensions into our production project and noticed some surprising breakages happening.

Removing EZSwiftExtensions fixed the issues.

We wonder if there is a subtle name clash going on with Apple internal method names since compiler did not give us any warning about conflicts.

When we ask Apple for support Apple Engineers recommended using a name prefix for extension names to their classes to avoid potential conflict.

Is there any other way to avoid name clash?

UISlider Extension

extension UISlider
{
  ///EZSE: Slider moving to value with animation duration
  public func setValue(value: Float, duration: Double) {
    UIView.animateWithDuration(duration, animations: { () -> Void in
      self.setValue(self.value, animated: true)

      }) { (bol) -> Void in
        UIView.animateWithDuration(duration, animations: { () -> Void in
          self.setValue(value, animated: true)
          }, completion: nil)
    }
  }
}

UIView.removeSubview(x,y)

Normally, you can only remove a subview if you have the object. In this method, you can remove a subview by having it's x and y
What do you guys think?

extension UIView {
  func removeSubview(x:Double,y:Double) {
    for view in self.subviews {
      if Float(view.frame.origin.x) == Float(x) && Float(view.frame.origin.y) == Float(y) {
        view.removeFromSuperview()
        "removed"
      }
    }
  }
}

StringExtensions -> CapitalizeFirst

add please at first line

guard characters.count > 0 else { return self }

because String().capitalizeFirst crashes the program. If someone would like to check on client side it's good but if someone not, it's not the expected behaviour to crash the program

Carthage support iOS SDK

Hi, when I use carthage to import the EZSwiftExtensions, I got the the error since the project base sdk is iOS 9.0 while mine is iOS 8.0, thus I have to modify the configuration manually and rebuild, can the author modify the project sdk to 8.0 thus we can keep our framework updated. No everyone's project use minimal sdk 9.0 right?

Document Directory

Don't know as of swift3 changes about this, but swift 2

NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last

just for getting document directory is not cool and swifty. Also I haven't found any methods by searching 'document' and 'directory'.

Carthage Support?

Im really excited for this repo, but I am wondering if there will be Carthage support anytime soon?

The `addKeyboardWillShowNotification()` and related methods are not type safe

public func addKeyboardWillShowNotification() {
        self.addNotificationObserver(UIKeyboardWillShowNotification, selector: "keyboardWillShowNotification:");
    }

public func addKeyboardDidShowNotification() {
    self.addNotificationObserver(UIKeyboardDidShowNotification, selector: "keyboardDidShowNotification:");
}

public func addKeyboardWillHideNotification() {
    self.addNotificationObserver(UIKeyboardWillHideNotification, selector: "keyboardWillHideNotification:");
}


public func addKeyboardDidHideNotification() {
    self.addNotificationObserver(UIKeyboardDidHideNotification, selector: "keyboardDidHideNotification:");
}

The above and related methods are not safe and it might easily cause a crash if the developer is not careful. It's better if we remove it or use a protocol to introduce safety.

Can't use on extensions

We are building a keyboard application and we can't use the pod in it. There is a problem with the UIAlertControllerExtension class. Here's the error:
EZSwiftExtensions/Sources/UIAlertControllerExtensions.swift:13:23: 'sharedApplication()' is unavailable: Use view controller based solutions where appropriate instead.

In my opinion, there should be a different sub pod for extensions that use Application so that we can still use the others in a non-application project.

Thoughts?

Document the code

Most of the code seems un-documented. We should add an appledoc style documentation.

Better UIImage resizing

Nowadays, to resize an UIImage, we gotta use this:

let image = UIImage(named: "img")
let image2 = UIImage.scaleTo(image: image, w: 50, h: 50)

In the example above, we're creating another UIImage from our UIImage, which is kinda confusing. In my opinion, we can make it better:

let image = UIImage(named: "img")
image.scaleTo(w: 50, h: 50)

What do you guys think? ๐Ÿค”

Add readme

Add new Array and Dictionary extensions into readme with examples

Wrong addAsChildViewController's calls order

Hey. According to Apple docs (section "Adding a Child View Controller to Your Content") you should first call addChildViewController and only then addSubview:

    /// now
    public func addAsChildViewController(vc: UIViewController, toView: UIView){
        toView.addSubview(vc.view)
        self.addChildViewController(vc)
        vc.didMoveToParentViewController(self)
    }

    /// how it should be
    public func addAsChildViewController(vc: UIViewController, toView: UIView){
        self.addChildViewController(vc)
        toView.addSubview(vc.view)
        vc.didMoveToParentViewController(self)
    }

I didn't experience any bugs, but still have some concerns. Should i submit PR?

carthage update problem

When I use carthage update failure and show many warning and error below info

*** Building scheme "EZSwiftExtensions-iOS" in EZSwiftExtensions.xcworkspace
config error: 'variable_name_min_length' is not a valid rule identifier
config error: 'valid_docs' is not a valid rule identifier
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution Run\ Script /Users/xxx/Library/Developer/Xcode/DerivedData/EZSwiftExtensions-hdalhogyszjhlnaluqlsmltwrjbs/Build/Intermediates/EZSwiftExtensions.build/Release-iphoneos/EZSwiftExtensions-iOS.build/Script-B27008081CAA12D5002177ED.sh
(1 failure)

capitalizeFirst should be a method

capitalizeFirst inside StringExtensions realizes an action of capitalizing the first character of a string, so therefore it should be a method instead of a variable with a getter.

Today's implementation:

    /// EZSE: Capitalizes first character of String
    public var capitalizeFirst: String {

        guard characters.count > 0 else { return self }
        var result = self

        result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return result
    }

What it should be:

    /// EZSE: Capitalizes first character of String
    public func capitalizeFirst() -> String {

        guard characters.count > 0 else { return self }
        var result = self

        result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return result
    }

Accessing app delegate

Hi,

Making app delegate easier to access won't lead to better code, because that pattern leads to circular dependencies. Please consider removing this part.

Good job on other parts of the library!

Thanks!

trimmed() String function behaves unexpected.

trimming string means removing special characters from start and end of string. trim() removes whitespace characters from inside string
e.g:

let string = "  Hello how are you   "
let` trimmedStr =  string.trimmed() // = '"Hellohowareyou"

While expected result is "Hello how are you"

UIColor Documentation

//
//  UIColorExtensions.swift
//  EZSwiftExtensions
//
//  Created by Goktug Yilmaz on 15/07/15.
//  Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit

extension UIColor {

    /// EZSE: init method with RGB values from 0 to 255, instead of 0 to 1. With alpha(default:1)
    public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
    }

    /// EZSE: init method with hex string and alpha(default: 1)
    public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
        var formatted = hexString.stringByReplacingOccurrencesOfString("0x", withString: "")
        formatted = formatted.stringByReplacingOccurrencesOfString("#", withString: "")
        if let hex = Int(formatted, radix: 16) {
          let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
          let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
          let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
          self.init(red: red, green: green, blue: blue, alpha: alpha)        } else {
            return nil
        }
    }

    /// EZSE: init method from Gray value and alpha(default:1)
    public convenience init(gray: CGFloat, alpha: CGFloat = 1) {
        self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha)
    }

    /// EZSE: Red component of UIColor (get-only)
    public var redComponent: Int {
        var r: CGFloat = 0
        getRed(&r, green: nil, blue: nil, alpha: nil)
        return Int(r * 255)
    }

    /// EZSE: Green component of UIColor (get-only)
    public var greenComponent: Int {
        var g: CGFloat = 0
        getRed(nil, green: &g, blue: nil, alpha: nil)
        return Int(g * 255)
    }

    /// EZSE: blue component of UIColor (get-only)
    public var blueComponent: Int {
        var b: CGFloat = 0
        getRed(nil, green: nil, blue: &b, alpha: nil)
        return Int(b * 255)
    }

    /// EZSE: Alpha of UIColor (get-only)
    public var alpha: Int {
        var a: CGFloat = 0
        getRed(nil, green: nil, blue: nil, alpha: &a)
        return Int(a)
    }

    /// EZSE: Returns random UIColor with random alpha(default: false)
    public static func randomColor(randomAlpha: Bool = false) -> UIColor {
        let randomRed = CGFloat.random()
        let randomGreen = CGFloat.random()
        let randomBlue = CGFloat.random()
        let alpha = randomAlpha ? CGFloat.random() : 1.0
        return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha)
    }

}

private extension CGFloat {
    /// SwiftRandom extension
    static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
        return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower
    }
}

isOnlyEmptySpacesAndNewLineCharacters() 39characters lengths

Just for testing string for not containing any useful information we need to call a 39-length method. Also I suggest to make it computable property instead of method.

Should we rename it to something like isWhitespaced
or
isSpaced (python-alike)
isStripped(python-alike)
isBlank (Java-alike)

Type safety hole

public mutating func removeObject<U: Equatable>(object: U) {
    for i in (0..<count).reverse() {
        if let obj = self[i] as? U where obj == object {
            self.removeAtIndex(i)
         }
     }
}

The above method seems to have a type safety hole at obj = self[i] as? U, which by the way, should have been obj = self[i] as! U in previous versions of Swift . The API is available for arrays that are not equatable as well. This is unsafe and prone to confusion and error. Also, no exceptions are thrown if the element isn't found.

We should refactor this to:

extension Array where Element : Equatable {
    public mutating func removeObject(object: Element) throws  {
        var index = 0
        for element in self {
            if object == element {
                self.removeAtIndex(index)
                return
            }
            index += 1
        }
        throw ArrayException.ObjectNotFound
     }
}

where ArrayException is

enum ArrayException : ErrorType {
    case ObjectNotFound
}

This is just an example we should apply this to all places where we are conditionally/forcefully downcasting to a type constraint.

Add methods and properties for NSDate

I think there should be a bit more methods and properties for NSDate. First, I know EXSwift had properties for elements such as day, month, year, etc. Those were pretty useful IMO.

Second, I think there should be methods to be able to easily determine if a NSDate is on the same day, same month or same year as another date instead of just having the == operator.

What do you think?

NSDate.tostring() not working as expected

fe7c2bf
30a8f79

I am trying to use this example and I run this code and get the following results:

    let format = "yyyy/MM/dd"
    let fromString = "2016/01/11"
    var date = NSDate(fromString: fromString, format: format)
    print(date) // Optional("2016/01/11 00:00:00 +0000")
    print(date?.toString())

Optional(2016-01-11 08:00:00 +0000)
Optional("12:00:00 AM")

I think toString() should include the whole date.
@furuyan

String documentation

Missing documentation for these methods:

///EZSE: Returns bold NSAttributedString
func bold() -> NSAttributedString {}

///EZSE: Returns underlined NSAttributedString
func underline() -> NSAttributedString {}  

///EZSE: Returns italic NSAttributedString
func italic() -> NSAttributedString {}

///EZSE: Returns NSAttributedString
func color(color: UIColor) -> NSAttributedString {}

NSAttributedString Extensions

Having NSAttributedString properties in String Extension would be useful. Some examples could be

let myStr = "Hello World"
let attrStr1 = myStr.undeline()
let attrStr2 = myStr.bold()
let attrStr3 = myStr.italic()
let attrStr4 = myStr[0...6].italic()
let attrStr5 = myStr[7...10].color(UIColor.greenColor())
let attrStr6 = myStr.link("www.google.com") // or href("www.google.com")
let attrStr7 = attrStr4.add(attrStr5).add(attrStr6)

Also chaining could be great. This would require extensions in both NSAttributedString and String

let attrStr1 = myStr.undeline().italic().link("www.google.com")

Slack/Gitter

Hi, I just thought whether it would be great to have Slack/Gitter so we could simplify communication of developing, improving this library.

Well, I suppose this will involve some new people to help improve library.

Maybe, just give a try. What do you think? Thumbs up/down, please :)

Load View/ViewController from Nib file

Now it looks like the following

let filterHeaderView = UINib(nibName: FilterHeaderView.className, bundle: nil).instantiateWithOwner(self, options: nil).last as? FilterHeaderView

Not as Swifty as it could be. Should we have an extension for that?

Well I don't actually know yet how it could be more swifty. Could anybody give an example? Something like let filterHeaderView = UINib.instantiate(view: FilterHeaderView) - loads nib from nil bundle with class name name, searches for view with passed class and returns it. Or something more controllable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.