Swift developed utility classes, mainly to provide regular expressions and other class extensions

Look directly at GitHub source

Add some new method extensions. For example: UIView extension, rich text extension, UIColor extension, thread-safe use extension

3. Some extensions of UIView

The main convenience is to directly control the view x, Y and so on a series of operations

This is relatively simple, not to introduce, mainly set,get, integration directly use on the line

extension UIView {

    var x: CGFloat {
        get {
            return frame.origin.x
        }
        set {
            frame = CGRect(x: newValue, y: frame.origin.y, width: frame.width, height: frame.height)
        }
    }
    ........................Copy the code

4. Thread-safe operations

References are made in Oc to prevent secure access to certain resources in multithreading

Synchronized operation, more about multithreading knowledge points I, here a large number of pages described, will make you get more harvest. No statements here

It has been removed in SwiftsynchronizedWe can directly use:

Objc_sync_enter // Resource operation objc_sync_exit

This can be done directly in conjunction with the use of closures

public func synchronized(_ lock: AnyObject, closure: () -> ()) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}Copy the code

You can perform the corresponding execution like this:

var test = 0
synchronized(test as AnyObject) {
    test = 1     // test is not changed by other threads in this scope
    print(test)
}
/// or so
synchronized(test as AnyObject, closure: {
    print(test)  // test is not changed by other threads in this scope
})Copy the code

So you can use it happily

5. Extensions to UIColor

We all know that Xcode from 8.0 can use color editor, image preview directly in code. This greatly saves our development efficiency

But in the use of sometimes habits, may be more or less with code to operate, here to bring you in the use of code when some of the convenience

Sometimes during the development process, the UI gives a color label such as 0xCE0755, so we sometimes need to convert, of course, in the color editor can be used directly.

The conversion is as follows:

public extension UIColor {

    /// Init color without divide 255.0
    ///
    /// - Parameters:
    /// - r: (0 ~ 255) red
    /// - g: (0 ~ 255) green
    /// - b: (0 ~ 255) blue
    /// - a: (0 ~ 1) alpha
    convenience init(r: Int, g: Int, b: Int, a: CGFloat) {
        self.init(red: CGFloat(r) / 255.green: CGFloat(g) / 255.blue: CGFloat(b) / 255.alpha: a)
    }

    /// Init color without divide 255.0
    ///
    /// - Parameters:
    /// - r: (0 ~ 255) red
    /// - g: (0 ~ 255) green
    /// - b: (0 ~ 1) alpha
    convenience init(r: Int, g: Int, b: Int) {
        self.init(r: r, g: g, b: b, a: 1)}/// Init color with hex code
    ///
    /// - Parameter hex: hex code (eg. 0x00eeee)
    convenience init(hex: Int) {
        self.init(r: (hex & 0xff0000) > >16.g: (hex & 0xff00) > >8.b: (hex & 0xff), a: 1)}}Copy the code

Here is to say that the main principle is: first through the & operation, obtain the corresponding color bit, and then by moving the corresponding number of bits to the left to carry out conversion. I won’t go into that here.portal

6. Some operations of rich text, the project is very clear introduction of the use, here do not make a statement.

Scientific notation conversion
Conversion of RMB amount

7. String extension, interception, insert operation

extension String {
    /// capture the first to any position
    ///
    /// -parameter end: indicates the end bit
    /// - Returns: truncated string
    func stringCut(end: Int) ->String{
        printLogDebug(self.characters.count)
        if! (end < characters.count) {return "Intercept out of range" }
        let sInde = index(startIndex, offsetBy: end)
        return substring(to: sInde)
    }

    /// intercept the person anywhere to the end
    ///
    /// - Parameter end:
    /// - Returns: truncated string
    func stringCutToEnd(star: Int) -> String {
        if! (star < characters.count) {return "Intercept out of range" }
        let sRang = index(startIndex, offsetBy: star).. <endIndexreturn substring(with: sRang)
    }

    /// Insert string at any position
    ///
    /// - Parameters:
    /// -content: insert content
    /// -locat: insert position
    /// - Returns: a string to be added
    func stringInsert(content: String.locat: Int) -> String {
        if! (locat < characters.count) {return "Intercept out of range" }
        let str1 = stringCut(end: locat)
        let str2 = stringCutToEnd(star: locat)
        return str1 + content + str2
    }
}Copy the code

8. Delay use, asynchronous delay, main thread execution

Use:

    let sleep = delay(0.7) {
        // execute the code
    }Copy the code

Do not want to execute during use

    cancel(sleep)Copy the code
The source code is as follows:
/ / MARK: use ____________________________________________________________________________________________________ delay

typealias Task = (_ cancel : Bool) -> Void

func delay(_ time: TimeInterval, task: @escaping ()->()) ->  Task? {

    func dispatch_later(block: @escaping ()->()) {
        let t = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: t, execute: block)
    }

    var closure: (()->Void)? = task
    var result: Task?

    let delayedClosure: Task = {
        cancel in
        if let internalClosure = closure {
            if (cancel == false) {
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        closure = nil
        result = nil
    }

    result = delayedClosure

    dispatch_later {
        if let delayedClosure = result {
            delayedClosure(false)}}returnresult } func cancel(_ task: Task?) { task? (true)}Copy the code

Updates continue, if you find it helpful to sponsor a star at 😋