使用随机生成的字符串查找Array字符串值的索引

时间:2014-12-07 18:10:34

标签: ios arrays swift nsuserdefaults for-in-loop

//
//  FactBook.swift
//  FunFacts
//
//  Created by Alex Macleod on 5/10/14.
//  Copyright (c) 2014 Alex Macleod. All rights reserved.
//

import Foundation

struct FactBook {
    let factsArray: NSArray = [
        "“The secret of being a bore... is to tell everything.” — Voltaire",
        "“The danger of success is that it makes us forget the world's dreadful injustice.” — Jules Renard",
        "“Blessed is the man who expects nothing, for he shall never be disappointed.”  — Alexander Pope",
        "“As children, we played hide and seek with one another, as adults with ourselves.” — Yahia Lababidi",
        "“When you run from discomfort all the time, you are restricted to a small zone of comfort” — Leo Babauta",
        "“To know you have enough is to be rich.” — Lao Tzu",
        "“Success is achieved when you combine mind, body, and technique.” — Sensei Yoshizo Machida",
        "“He who knows others is wise; He who know himself is enlightened.” — Lao Tzu",
        "“Do not spoil what you have by desiring what you have not.” — Epicurus",
        "“If there is something that must be done, it is better not to rely on others.” — Hagakure",
        "“It's not good to settle into a set of opinions; it's a mistake to put in effort and obtain some understanding and stop at that.” — Hagakure",
        "“People let the same problem make them miserable for years when they could just say 'so what'.” — Andy Warhol",
        "“Man needs difficulties; they are necessary for health.” — Carl Jung",
        "“Men of profound sadness betray themselves when they are happy.” — F. Nietzsche",
        "“He who controls others may be powerful, but he who has mastered himself is mightier still.” — Lao Tzu",
        "“Fiction is a branch of neurology: the scenarios of nerve and blood vessels are the written mythologies of memory and desire.” — J.G. Ballard",
        "“Unhappy parents teach you a lesson that lasts a lifetime.” — J.G. Ballard",
        "“The less men think, the more they talk.” — Montesquieu",
        "“I had no shoes and complained, until I met a man who had no feet.” — Indian Proverb",
        "“Fools talk, cowards are silent, wise men listen.” — Carlos Ruiz Zafón",
        "“Zen is not some kind of excitement, but concentration on our usual everyday routine.” — Shunryu Suzuki",
        "“The man who does not read good books has no advantage over the man who can't read them.” — Mark Twain",
        "“He who laughs at himself never runs out of things to laugh at.” — Epictetus",
        "“You should sit in meditation for twenty minutes a day, unless you are too busy. Then you should sit for an hour.” — Zen Proverb",
        "“Train yourself to let go of everything you fear to lose.” — Yoda",
        "“Muddy water is best cleared by leaving it alone.” — Alan Watts",
        "“Maybe you have to know the darkness before you can appreciate the light.” —  Madeleine L’Engle",
        "“We can’t selectively numb emotion. Numb the dark and you numb the light.” —  Brené Brown",
        "“It is useless to hold a person to anything he says while he is in love, drunk, or running for office.” — Shirley Maclaine",
        "“The awareness of emptiness brings forth a heart of compassion.” — Gary Snyder",
        "“Beware those who seek constant crowds for they are nothing alone.” — Charles Bukowski",
        "“Be brave. Take risks. Nothing can substitute experience.” — Paulo Coelho",
        "“When you get there, there isn’t any there there.” — Zen Proverb",
        "“If you chase two rabbits, you will not catch either one.” — Russian Proverb",
        "“True friendship resists time, distance and silence.” — Isabel Allende",
        "“Inspiration exists, but it must find you working.” — Pablo Picasso",
        "“Expect more get less and feel sadness, or: expect less get more and feel happiness.” — Vijay Dhameliya",
        "“Read books when you are free, read minds when you aren't.” — Rabindranath Tagore",
        "“Definitions belong to the definers, not the defined.” — Toni Morrison",
        "“You meet your destiny on the road you take to avoid it.” — Carl Jung",
        "“We learn from history that we do not learn from history” — Hegel",
        "“You should sit in meditation for twenty minutes a day, unless you are too busy. Then you should sit for an hour.” — Zen Proverb",
        "“From my rotting body flowers shall grow and I am in them and that is eternity.” — Edvard Munch",
        "“Great things are not accomplished by those who yield to trends and fads and popular opinion.” — Jack Kerouac",
        "“Good people do not need laws to tell them to act responsibly.” — Plato",
        "“If there is to be any peace it will come through being, not having.” — Henry Miller",
        "“Some people are born on third base and go through life thinking they hit a triple.” — Barry Switzer",
        "“You can tell more about a person by what he says about others than you can by what others say about him.” — Audrey Hepburn",
        "“If you really want to see why you do things, then don’t do them and see what happens.” — Michael A. Singer",
        "“When you’re afraid of someone’s judgment, you can’t connect with them. You’re too preoccupied with impressing them.” — Amanda Palmer",
        "“Having no destination, I am never lost.” — Ikkyu",
        "“Beliefs are neat. Cherish them, but don’t share them like they’re the truth.” — Bill Hicks",
        "“A day without laughter is a day wasted.” — Charlie Chaplin",
        "“Now and then it's good to pause in our pursuit of happiness and just be happy.” — Guillaume Apollinaire",
        "“Out of your vulnerabilities will come your strength.” — Sigmund Freud",
        "“When another person makes you suffer, it is because he suffers deeply within himself, and his suffering is spilling over.” — Thich Nhat Hanh",
        "“Man suffers only because he takes seriously what’s made for fun.” — Alan Wilson Watts",
        "“What would your current frustrations look like from the vantage point of the final days of your life?” — Taro Gold",
        "“It does not matter how slowly you go as long as you do not stop.” — Confucius",
        "“The only way to make sense out of change is to plunge into it, move with it, and join the dance.” — Alan Watts",
        "“Creativity is the greatest rebellion.” — Osho"]

    func randomFact() -> String? {
        var arrayLength = UInt32(factsArray.count)
        var randomNumber = Int(arc4random_uniform(arrayLength))
        var finalRandomNumber = Int(randomNumber)

        return factsArray[finalRandomNumber] as NSString
    }

    func quoteIndexArray() {

        var i: NSString! = NSUserDefaults.standardUserDefaults().objectForKey("firstQuote") as? NSString

        println(i)

//        var currentIndex: NSString? = factsArray.valueForKey(i) as? NSString
//        
//        println(currentIndex)

        for (index, value) in enumerate(factsArray) {
//            println("Item \(index + 1): \(value)")
            if i as NSString == factsArray as NSArray {
                println("Item \(index): \(value)")
            } else {
                println("nothing")
            }
        }



//        for i in factsArray {
//            if i as NSObject == factsArray {
//                println("something")
//            } else {
//                println("nothing")
//            }
//        }

    }

//    func wikiUrl() -> String? {
//        var wikiUrls: [Int: String] = [0: "www.Toronto Pearson",
//            1: "Dublin"]
//        
//        var i: NSString! = NSUserDefaults.standardUserDefaults().objectForKey("firstQuote") as? NSString
//        
//        println(i)
//        
//        for (key,url) in wikiUrls {
//            if i == 0 {
//                println(0, "www.ulr.com")
//            }
//        }
//        
//        return nil
//    }
}

我有一个充满引号的“factsArray”。 randomFact()函数从“factsArray”中随机选择一个引号,返回值显示在我的视图控制器上的标签中。

我将视图控制器上显示的引号保存到NSUserDefaults。在quoteIndexArray()函数内部,我试图将此字符串保存在NSUserDefaults中,并使用for in循环将其与我的“factsArray”中的字符串匹配...然后返回索引那个价值。

对于那么容易的事情有严重的麻烦。有人请引导我进入光明。提前谢谢!

3 个答案:

答案 0 :(得分:1)

简单到(直接比较):

for (index, value) in enumerate(factsArray) {
     if(i == value) {
          println("Item \(index): \(value)")
     }
}

答案 1 :(得分:1)

我同意上述评论,即更容易存储<​​em>索引 用户默认值中的字符串

如果不可能: NSArray有一个indexOfObject()方法,它返回对象的第一个索引 在数组中:

let index = factsArray.indexOfObject(i)
if index != NSNotFound {
    println(index)
} else {
    println("not found")
}

或者,您可以将NSArray桥接到Swift [String]数组 并使用find()函数:

if let index = find(factsArray as [String], i) {
    println(index)
} else {
    println("not found")
}

答案 2 :(得分:0)

您的条件似乎没有意义。当您将字符串与NSArray类型的对象进行比较时,if i as NSString == factsArray as NSArray应始终评估为false。如果您改为检查if i as NSString == value,那么您将检查存储在数组中的值是否相等。

此外,我不知道你在NSUserDefaults上写下你的报价的地方(获得批准,或许你在其他地方做过这样的工作)。