Skip to content

Instantly share code, notes, and snippets.

@object2dot0
Created May 7, 2017 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save object2dot0/f28f2431b80664ef72a0f1930f9074c2 to your computer and use it in GitHub Desktop.
Save object2dot0/f28f2431b80664ef72a0f1930f9074c2 to your computer and use it in GitHub Desktop.
Optimizing your Swift Codebase with Attributes

Link: https://www.buddybuild.com/blog/optimizing-your-swift-codebase-with-attributes

@available(args)

Indicates the avalibility of a method of a platform or version number

@available(iOS 10.0, macOS 10.12) 
@available(iOS 10.0, macOS 10.12, *)
@available(*, deprecated: 1.3)

iOS iOSApplicationExtension macOS macOSApplicationExtension watchOS watchOSApplicationExtension tvOS tvOSApplicationExtension

@discardableResult

The result and be discarded withour writing any variable for return type, Prevents the compiler error

@discardableResult func anOldInsaneFunction() -> String

@autoclosure

The @autoclosure is another handy attribute that adds clarity to your codebase. It automatically wraps a closure that’s supplied as an argument. Since the closure doesn’t take any arguments itself, it’ll return the actual value of the expression that’s wrapped within it.

func XCTAssertEqual<T>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line) where T : Equatable  

  XCTAssertEqual(aDev.pay + raiseAmount, 750000, "Unexpected salary after raise was applied.")
  
  func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line)  

@escaping

The @escaping attribute signifies that the passed in closure can outlast the function it’s passed to. By default Swift 3 has non escaping closures.

func evaluatePayRaise(withAccolades raiseEvaluation:@escaping @autoclosure ()->Bool)
    {
        if raiseEvaluation()
        {
            //Give them a raise, and then save it to their records
            previousPayRaiseEvaluations.append(raiseEvaluation)
        }
    }
    
    
  aProgrammer.evaluatePayRaise(withAccolades: aProgrammer.isSenior && aProgrammer.appsShipped > 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment