alemac852
alemac852

Reputation: 109

Find the index of an Array string value using a randomly generated string

//
//  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
//    }
}

I have a "factsArray" full of quotes. The randomFact() function selects a quote at random from the "factsArray" and the return value gets displayed in a label on my view controller.

I save the quote displayed on my view controller into NSUserDefaults. Inside the quoteIndexArray() function I am trying to take this string saved in NSUserDefaults and match it up with a string in my "factsArray" using a for in loop... then return the index of that value.

Having serious trouble with something that is so easy. Someone please guide me into the light. Thanks in advance!

Upvotes: 0

Views: 779

Answers (3)

Martin R
Martin R

Reputation: 539795

I agree with above comment that it would be easer to store the index instead of the string in the user defaults.

If that is not possible: NSArray has a indexOfObject() method which returns the first index of an object in an array:

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

Alternatively, you can bridge the NSArray to a Swift [String] array and use the find() function:

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

Upvotes: 1

hasan
hasan

Reputation: 24185

As simple as (direct comparison):

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

Upvotes: 1

user1078170
user1078170

Reputation:

Your conditional doesn't seem to make sense. if i as NSString == factsArray as NSArray should always valuate to false as you are comparing a string for equality with an object of type NSArray. If you instead check if i as NSString == value, then you will be checking for equality with the values stored in your array.

Additionally, I don't see where you are writing your quote to NSUserDefaults (granted, perhaps you're doing that elsewhere and it's working).

Upvotes: 0

Related Questions