Cowboy Tech

CodePractice

字符串

将数组中的最后一个字符合并

var nonsenseArray = ["bungalow", "buffalo", "indigo", "although", "Ontario", "albino", "%$&#!"]

func combineLastCharacters(wordArray:[String]) -> String {

    var newWord = ""
    for var word in wordArray {
        let lastCharacter = word.removeAtIndex(word.endIndex.predecessor())
        newWord.append(lastCharacter)
    }
    return newWord
}

combineLastCharacters(nonsenseArray)

//output :"woohoo!"

字符串中有数字则返回true,字符则false

//创建只有数字的set
let digits = NSCharacterSet.decimalDigitCharacterSet()

func digitsOnly(word: String) -> Bool {

    for character in word.unicodeScalars {

        if !digits.longCharacterIsMember(character.value) {
            return false
        }
    }
    return true
}

digitsOnly("123")  //output : true

digitsOnly("12a")  //output : false

数组

去除掉数组中四个字母的字符串

let dirtyWordsArray = ["phooey", "darn", "drat", "blurgh", "jupiters", "argh", "fudge"]

func cleanUp(dirtyArray: [String]) -> [String] {
    var cleanArray = [String]()
    for word in dirtyArray {
        if word.characters.count == 4 {
        } else {
            cleanArray.append(word)
        }
    }
    return cleanArray
}

cleanUp(dirtyWordsArray) //output : ["phooey", "blurgh", "jupiters", "fudge"]

字典

筛选出字典中指定value的key值数组

var movies:Dictionary<String,String> = [ "Boyhood":"Richard Linklater","Inception":"Christopher Nolan", "The Hurt Locker":"Kathryn Bigelow", "Selma":"Ava Du Vernay", "Interstellar":"Christopher Nolan"]

class MovieArchive {
    func filterByDirector(currentDirector:String, movies: Dictionary<String, String>) -> [String] {
        var filteredArray = [String]()
        for (movie, director) in movies {
            if director == currentDirector {
                filteredArray.append(movie)
            }
        }
        return filteredArray
    }
}

// Solution
var myArchive = MovieArchive()
myArchive.filterByDirector("Richard Linklater", movies: movies)    //output : ["Boyhood"]

UIView

Fade Out and Fade in

@IBAction func sunRiseAndSet(sender: AnyObject) {
       // Fade out

       UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {

           self.imageView.alpha = 0.0

           }, completion: {
               (finished: Bool) -> Void in

               //Once the label is completely invisible, set the text and fade it back in
               if (self.imageView.image == UIImage(named: "sunrise")) {
                   self.imageView.image = UIImage(named:"sunset")!
               } else {
                   self.imageView.image = UIImage(named:"sunrise")!
               }

               // Fade in
               UIView.animateWithDuration(1.0, delay:0.0, options:UIViewAnimationOptions.CurveEaseIn, animations: {
                   self.imageView.alpha = 1.0
                   }, completion: nil)
       })
   }