working on it ...

Filters

Explore Public Snippets

Sort by

Found 16k snippets matching: swift

    public by WadeCantley modified Dec 9, 2014  4688875  55  8  1

    iOS - Swift - Add a Done button to a Keyboard Tool Bar

    Adding a done button to the keyboard tool bar and working within the textField delegate to make that happen. In this situation the keyboard is a number pad which doesn't have its own done button.
    //MARK: - Helper Methods
        
    // This is called to remove the first responder for the text field.
    func resign() {
        self.resignFirstResponder()
    }
        
    // This triggers the textFieldDidEndEditing method that has the textField within it.  
    //  This then triggers the resign() method to remove the keyboard.
    //  We use this in the "done" button action.
    func endEditingNow(){
        self.view.endEditing(true)
    }
        
        
    //MARK: - Delegate Methods
        
    // When clicking on the field, use this method.
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    
            
        // Create a button bar for the number pad
        let keyboardDoneButtonView = UIToolbar()
        keyboardDoneButtonView.sizeToFit()
            
        // Setup the buttons to be put in the system.
        let item = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("endEditingNow") )
        var toolbarButtons = [item]
            
        //Put the buttons into the ToolBar and display the tool bar
        keyboardDoneButtonView.setItems(toolbarButtons, animated: false)
        textField.inputAccessoryView = keyboardDoneButtonView
    
        return true
    }
        
    // What to do when a user finishes editting
    func textFieldDidEndEditing(textField: UITextField) {
            
        //nothing fancy here, just trigger the resign() method to close the keyboard.
        resign()
    }
        
        
    // Clicking away from the keyboard will remove the keyboard.
    override func touchesBegan(touches: (NSSet!), withEvent event: (UIEvent!)) {
        self.view.endEditing(true)
    }
        
    // called when 'return' key pressed. return NO to ignore.
    // Requires having the text fields using the view controller as the delegate.
    func textFieldShouldReturn(textField: UITextField!) -> Bool {
            
        // Sends the keyboard away when pressing the "done" button
        resign()
        return true
            
    }
    
    

    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 mirage3d modified Mar 16, 2016  289605  9  4  0

    Get localised country list from Cocoa in Swift

    import Cocoa
    
    let currentLocale = NSLocale.currentLocale()
    let countryCodes = NSLocale.ISOCountryCodes()
    let countryNames = countryCodes.map { currentLocale.displayNameForKey(NSLocaleCountryCode, value: $0) }
    	.filter { $0 != nil }
    	.sort(<)

    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 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  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 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 Jun 23, 2014  4132  1  6  1

    How do you map over the values of Zip2 in Swift?

    foo has the type ZipGenerator2, IndexingGenerator?.
    The following will get you an array from the return value of Zip2:
    
    var myZip = Zip2([1, 2, 3], ["a", "b", "c"]).generate()
    var myZipArray: Array<(Int, String)> = []
    
    while let elem = myZip.next() {
        myZipArray += elem
    }
    
    println(myZipArray)    // [(1, a), (2, b), (3, c)]
    -- UPDATE: EVEN BETTER! --
    
    let myZip = Zip2([1, 2, 3], ["a", "b", "c"])
    let myZipArray = Array(myZip)
    
    println(myZipArray)    // [(1, a), (2, b), (3, c)]
    -- now for fun --
    
    I'm going to guess that we can init a new Array with anything that responds to generate() ?
    
    println(Array("abcde"))  // [a, b, c, d, e]

    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 &amp; 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  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 Snippets
    • Channels Snippets