working on it ...

Filters

snippets
34
followers
25
Published by snip2code

ObjectiveC

This channel collects useful snippets for ObjectiveC language
Sort by

Found 31 snippets

    public by snip2code modified Aug 13, 2017  117  0  3  1

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by marksimon232 modified Jul 6, 2015  3223  2  6  0

    Swift: .max and .min properties

    If you have code around that uses lots of F’s (e.g. 0xFFFFFFFF) or capital letters (e.g. UINT32_MAX), consider replacing these constants with built-in Swift versions.
    Swift offers .max and .min properties for many numeric types. For example:
    
    public func Random01() -> Double {
        return Double(arc4random()) / Double(UInt32.max)
    }

    public by marksimon232 modified Jul 6, 2015  3337  0  6  0

    Swift2: DebugPrint differentiation

    Find items that printed differently in debugPrint than they did in print.
    import Cocoa
    
    // Items to check
    //let x = "Snoop"
    //let x = 1...5
    let x = UnicodeScalar(0x1f601)
    
    // Build test cases
    var a = ""; print(x, &a, appendNewline:false); print(a)
    var b = ""; debugPrint(x, &b, appendNewline:false); print(b)
    
    // Compare and alert
    func ExitAfter(t: Double, _ status: Int32) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
            numericCast(UInt64(t * Double(NSEC_PER_SEC)))), 
            dispatch_get_global_queue(
                DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
            {exit(status)})
    }
    
    if a != b {
        // Success
        print("YES!")
        NSSound(named: "Sosumi")?.play()
        ExitAfter(0.5, 0)
        CFRunLoopRun() // stick around to produce sound
    } else {print("No")}

    public by marksimon232 modified Jul 6, 2015  4272  2  6  1

    Swift 2: Creating the date Formatter

    internal func BuildSimpleTimeFormatter() -> NSDateFormatter {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("mm:ss:SSS", options: 0, locale: NSLocale.currentLocale())
        return dateFormatter
    }
    
    internal let dateFormatter = BuildSimpleTimeFormatter()
    
    public func SWLog(format: String, _ args: CVarArgType...) {
        #if DEBUG
            let timeString = dateFormatter.stringFromDate(NSDate())
            print("\(timeString): " + String(format: format, arguments: args), &errStream)
        #endif
    }

    public by marksimon232 modified Jul 6, 2015  2750  0  7  1

    Swift: Revisiting printing with string formats

    You pass NSLog a format string followed by a variadic list of Objective-C-compatible parameters. 
    The parameters map to specifiers embedded within the format string.
    
    NSLog("Dictionary: %@, Double: %0.2f", ["Hello":3], 2.7)            

    public by marksimon232 modified Jul 6, 2015  282996  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by micheleaiello modified Jan 16, 2015  2513  0  5  0

    Open Settings (iOS 8 or above)

    BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
    if (canOpenSettings) {
      NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
      [[UIApplication sharedApplication] openURL:settingsURL];
    }

    public by marksimon232 modified Oct 21, 2014  2237  0  7  2

    Swift Collections: Classes vs. Structs - where to use which?

    A small distinction in behavior drives the architectural possibilities at play here: structs are value types and classes are reference types.
    Why you should consider using Structs instead of Classes when writing Swift?
    
    Instances of value types are copied whenever they’re assigned or used as a 
    function argument. Numbers, strings, arrays, dictionaries, enums, tuples, and 
    structs are value types. For example:
    
    var a = "Hello"
    var b = a
    b.extend(", world")
    println("a: \(a); b: \(b)") // a: Hello; b: Hello, world
    
    Instances of reference types (chiefly: classes, functions) can have multiple 
    owners. When assigning a reference to a new variable or passing it to a 
    function, those locations all point to the same instance. This is the behavior
    you’re used to with objects. For instance:
    
    var a = UIView()
    var b = a
    b.alpha = 0.5
    println("a: \(a.alpha); b: \(b.alpha)") // a: 0.5; b: 0.5
    
    The distinction between these two categories seems small, but the choice 
    between values and references can have huge ramifications for your system’s
    architecture.
    
    

    public by marksimon232 modified Aug 12, 2014  3379  2  6  0

    Swift Collections: Swift Array reference Snippets

    Swift makes creating and modifying arrays really easy. When you create your array, you don’t have to initialize it with a certain type, if all of your given values are the same type.
    Example: If you create an array and all of the initial values are Strings, Swift automatically infers that the array will be a string array.
      
    => Creating a mutable array:
    Notice that the beginning of the line begins with var, which means variable and allows the contents of the array to be changed in the future.
    var cityArray = ["Portland","San Francisco","Cupertino"]
    
    
    => Creating an immutable array:
    Notice that the beginning of the line begins with let, which means constant and means the contents can not be changed in the future.
    let cityArray = ["Portland","San Francisco","Cupertino"]
    
    
    => Creating an empty array:
    If you need to create an empty array, you must initialize it with the type of object that will be added later.
    var animalArray = String[]()
    //This array will only allow strings.
     
    var animalAgeArray = Int[]()
    //This array will only hold integers, nothing else.
    
    
    => Creating an array to hold a specific type:
    This variable array will only hold string objects, nothing else.
    var cityArray: String[] = ["Portland","San Francisco","Cupertino"]
    
    This variable array will only hold integers, nothing else.
    var numberArray:Int[] = [1,3,4]
    
    
    => Counting number of items inside an array:
    Use the read-only count property to count the number of items in an array.
    var cityArray: String[] = ["Portland","San Francisco","Cupertino"]
    let count = cityArray.count
    //count = 3
    
    
    => Check if array is empty:
    Use the Boolean isEmpty as a quick way to determine if an array is empty.
    var cityArray: String[] = ["Portland","San Francisco","Cupertino"]
    
    if cityArray.isEmpty {
        println("Empty") 
    }else{
        println("Not Empty")
    }
    //prints "Not Empty"
    
    
    => Add an item to the end of an array:
    var cityArray: String[] = ["Portland","San Francisco","Cupertino"]
    cityArray.append("Seattle")
    //The array now contains 4 items
    
    Alternately, you can use the addition assignment operator (+=) to quickly add an item.
    cityArray += "Seattle"
    
    
    => Add an array of items to an existing array:
    Use the addition assignment operator (+=) to quickly add an array of items.
    
    var cityArray: String[] = ["Portland","San Francisco","Cupertino","Seattle"]
    cityArray += ["Vancouver", "Los Angeles", "Eugene"]
    //The array now contains 7 items
    
    
    Alternately, if you have already created an array:
    
    var cityArrayA: String[] = ["Portland","San Francisco","Cupertino","Seattle"]
    var cityArrayB: String[] = ["Vancouver", "Los Angeles", "Eugene"]
    cityArrayA += cityArrayB;
    
    //cityArrayA now contains 7 items.
    
    
    => Change a value inside an array:
    Pass the index of the value you wish to change, along with the new value.
    
    var cityArray: String[] = ["Portland","San Francisco","Cupertino","Seattle"]
    cityArray[0] = "Portland, Oregon"
    //cityArray is now ["Portland, Oregon", "San Francisco", "Cupertino", "Seattle"]
    
    
    => Changing multiple values inside an array:
    Swift makes it easy to change multiple values inside an array at once. Using the subscript syntax, you provide the index of the items you wish to modify as well as the new additions.
    
    var cityArray = ["Portland, Oregon","San Francisco","Cupertino","Seattle"]
    cityArray[1...3] = ["San Francisco, California","Cupertino, California","Seattle, Washington"]
    
    //We replaced the values at indexes 1,2 & 3 and now cityArray contains:
     ["San Francisco, California", "Cupertino, California", "Seattle, Washington"]
    
    
    Note: The amount of replacement items does not have to equal the length of the items you are replacing
    Example:
    
    var cityArray: String[] = ["Portland, Oregon","San Francisco","Cupertino","Seattle"]
    cityArray[1...3] = ["San Francisco, California","Cupertino, California"]
    //cityArray contains: ["Portland, Oregon", "San Francisco, California", "Cupertino, California"]
    Even though we tell the cityArray to replace indexes 1 through 3, we only give 2 values back to the array.
    
    
    
    => Removing a value from a specific index:
    var animalArray: String[] = ["Dog", "Cat", "Fish", "Owl", "Beaver"]
    animalArray.removeAtIndex(4)
    //animalArray now contains: ["Dog", "Cat", "Fish", "Owl"]
    
    
    Alternately, if you wish to save the value before you remove it:
    let stringAnimal = animalArray.removeAtIndex(4)
    //Saves "Beaver" to the string constant stringAnimal and also removes it from the array.
    
    
    => Removing the last value of an array:
    To avoid having to call count on an array, Swift allows developers to simply call removeLast to remove the last item in an array.
    
    var animalArray: String[] = ["Dog", "Cat", "Fish", "Owl" ]
    animalArray.removeLast
    //animalArray now contains 3 items, "Owl" has been removed.
    
    
    Again, if you wish to save the value before you remove it:
    
    let stringAnimal = animalArray.removeLast
    //Saves "Owl" (which was the last item in the array) to the string constant stringAnimal and also removes it from the array.
    
    
    => Removing all items:
    To remove all items from an array, use the removeAll method.
    
    var animalArray: String[] = ["Dog", "Cat", "Fish", "Owl" ]
    animalArray.removeAll()
    //animalArray is now empty.
    
    
    => Keeping the capacity of the array:
    animalArray.removeAll(keepCapacity: true)
    //animalArray is now empty but the capacity is kept at 4.
    
    
    => Iterating over an array:
    Simple for in Loop
    
    for animal in animalArray {
    
        println(animal)
    
    }
    //Prints each animal name into the console.
    
    
    for in Loop + Enumeration
    If you want to have the index of the item as well, you must use the enumerate function with your loop. The enumerate function returns a Tuple for each value in the array.
    
    for(index,animal) in enumerate(animalArray) {
    
        println("The \(animal) is at index:\(index")
    }
    
    //Output: 
    //The Dog is at index:0
    //The Cat is at index:1
    //The Fish is at index:2
    //The Owl is at index:3
    
    
    => Reversing the values in an array:
    var animalArray: String[] = ["Dog", "Cat", "Fish", "Owl" ]
    animalArray.reverse()
    
    //The array values are now ["Owl", "Fish", "Cat", "Dog"]
    
    
    => Create a new array from the reversed values:
    var animalArray: String[] = ["Dog", "Cat", "Fish", "Owl" ]
    let newArray = animalArray.reverse()
    //The newly created array contains ["Owl", "Fish", "Cat", "Dog"]

    public by marksimon232 modified Aug 12, 2014  4557  7  6  2

    Swift Collections: Function with multiple return values

    I want my function to get the current time and the date formatted as Strings.
    => Objective-C:
    Objective-C doesn’t support a function returning multiple values. The closest you can get would be to create your values add them to a NSDictionary and return the dictionary. 
    
    
    => Swift:
    In Swift, we include the return arrow “->” which specifies that the function will return and a tuple with the types we wish to be returned. A tuple type is simply a comma-separated list of zero or more types, enclosed in parentheses.
        func getCurrentDateAndTime() -> (date: String, time: String) {
            
            let date = NSDate() //Get current date
            
            //Formatter for time
            let formatterTime = NSDateFormatter()
            formatterTime.timeStyle = .ShortStyle //Set style of time
            var timeString = formatterTime.stringFromDate(date) //Convert to String
    
    
            //Formatter for date
            let formatterDate = NSDateFormatter()
            formatterDate.dateStyle = .ShortStyle //Set style of date
            var dateString = formatterDate.stringFromDate(date) //Convert to String
    
            return (dateString, timeString) //Returns a Tuple type
            
        }
        
    To call this method within the same class:
            let time = getCurrentDateAndTime()
            println(time.date)
            println(time.time)
            
    //Results in the getCurrentDateAndTime function being called and the current date & time printed to the console. Notice how simply the values can be accessed from the returned Tuple;
    • Public Snippets
    • Channels Snippets