working on it ...

Filters

snippets
25
followers
14
Published by marksimon232

Swift X-Code 6 for iOS 8

Swift X-Code 6 for iOS 8
Sort by

Found 20 snippets

    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 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 Oct 21, 2014  5916  1  7  0

    Swift Collections: Convert String to float in Apple's Swift?

    If you're trying to convert numbers taken from a UITextField, which I presume are actually strings, and convert them to a float, so I can multiply them.
    I believe the current best way to achieve this is to use:
    
    var WageConversion = Wage.text.bridgeToObjectiveC().floatValue
    This is a good implementation since it can handle actual floats (input with .) and will also help prevent the user from copying text into your input field (12p.34, or even 12.12.41).
    
    Also, variables and constants should start with a lower case (including IBOutlets)

    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 by marksimon232 modified Aug 12, 2014  3101  0  6  1

    Swift Collections: Simple function with return value

    I want to our function to get the current time, formatted and returned as a String.
    => Objective-C:
    -(NSString *)getCurrentTime {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
    
        return currentTime;
        
    }
    
    To call this method within the same class:
    NSString *time = [self getCurrentTime];
    NSLog(@"%@",time);
    //Results in the getCurrentTime function being called and the current time printed to the console.
    
    
    => Swift 
    In Swift, we include the return arrow “->” which specifies that the function will return and the type of object that will be returned (String).
        func getCurrentTime() -> String {
            
            let date = NSDate()
            let formatter = NSDateFormatter()
            formatter.timeStyle = .ShortStyle
            var stringValue = formatter.stringFromDate(date)
            
            return stringValue
            
        }
        
    To call this method within the same class:
    let time = getCurrentTime()
    println(time)
    //Results in the getCurrentTime function being called and the current time printed to the console.

    public by marksimon232 modified Aug 12, 2014  2807  0  6  1

    Swift Collections: Simple function with parameter

    I want to pass a name (String) to a function and then print it out to the console.
    => Objective-C:
    -(void)outputName:(NSString *)nameString {
    
       NSLog(@"My name is %@",nameString);
    
    }
    
    To call this method within the same class:
    [self outputName:@"Mark"];
    //Results in the outputName function being called and "My name is Mark" printed to the console.
    
    
    => Swift:
    In Swift, we define the input value first (in our case, the string value), followed by the Type (String).
    func outputName(nameString:String){
    
        println("My name is: \(nameString)")
    
    }
    To call this method within the same class:
    outputName(@"Mark")
    //Results in the outputName function being called and "My name is Mark" printed to the console.

    public by marksimon232 modified Aug 12, 2014  1933  0  6  1

    Swift Collections: Simple function

    Objective-C:
    -(void)printText {
    
        NSLog(@"Printing this line to the console");
    
    }
    
    
    Swift:
    func printText(){
    
        println("Printing this line to the console")
    
    }

    public by marksimon232 modified Aug 9, 2014  3996  1  7  1

    Swift Collections: Create UIAlertViews in Swift (iOS 8)

    This is how you make an alert popup on your iPhone application.
    For beginners UIAlertViews were, on iOS 7, one of the main ways that iOS Developers had to 
    let the app users know something important about the application and its 
    current state. UIActionSheet was sort of the same thing, but with more 
    action-based focus, prompting the user to do something.
    
    On iOS 8 these two classes have been merged into one, called UIAlertController.
    We can display a message to the user doing the following:
    
    ----------------
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alert, animated: true, completion: nil)
    ----------------
    
    That will display a message to the user, but with no buttons so the user can take any action. Also, note that the constructor for the UIAlertController object accepts a preferredStyle param, which can be anyone of the following:
    
    .Alert: shows the message to the user at the center of the screen.
    .ActionSheet: shows the message to the user at the bottom of the screen.
    
    => Actions
    So far we’ve showed the user a message, but we haven’t provided them a way
    to give feedback to us. Enter UIAlertAction. This class has a closure-based 
    syntax and allows us to add buttons to a UIAlertController object, and 
    define what should happen when the user taps that button.
    
    ----------------
    var alert = ....
    
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in
    
    // What happens when the user taps 'Ok'? That goes in here
    
    }))
    
    self.presentViewController(alert, animated: true, completion: nil)
    ----------------
    
    The UIAlertAction constructor accepts three params: a title (String), a 
    style (UIAlertActionStyle) and a handle (a closure). The style of the 
    UIAlertAction object can be anyone of the following:
    
    .Destructive: renders the title property on red
    .Default
    .Cancel
    
    We can add as many UIAlertActions to a UIAlertController as we want, just be careful not to give your users too many options. Keep things simple.

    public by marksimon232 modified Jul 11, 2014  1997  0  6  2

    Swift Collections: Calling a delegate method

    Objective-C:
    In Objective-C, often times, you would see an If statement to check if there 
    was an object assigned to the delegate property before calling the delegate 
    method.
    
    if (self.delegate)
        [self.delegate someMethod];
    
    -----------------------
    
    Swift:
    In Swift, you can take advantage of the question mark syntax. If the 
    delegate property is empty, nothing after the question mark will be executed.
    
    delegate?.someMethod()
    
    
    • Public Snippets
    • Channels Snippets