Reputation: 1572
I have a function, which is used to shuffle an array. This function is working fine in playground but when I am trying to implement it on my project I am having an error.
Here is the code:
import UIKit
import Darwin
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func shuffle<C: MutableCollectionType where C.Index.Distance == Int>(var list: C) -> C {
var n = count(list)
if n == 0 { return list }
let oneBeforeEnd = advance(list.startIndex, n.predecessor())
for i in list.startIndex..<oneBeforeEnd {
let ran = Int(arc4random_uniform(UInt32(n--)))
let j = advance(i,ran)
swap(&list[i], &list[j])
}
return list
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(numbers)
}
The error is occurring when I am calling shuffle()
saying expected declaration
. Can anyone tell me where should I add the function or should I do something to implement correctly this code.
Upvotes: 0
Views: 86
Reputation: 57124
You have to move the call of shuffle
to the body of any method. For example viewDidLoad
. You either have to move the declaration and definition of the numbers
to there too - or at least move it to the start of the class declaration:
class ViewController: UIViewController {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // either have the var decl here
override func viewDidLoad() {
super.viewDidLoad()
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // or here
shuffle(numbers)
}
...
func shuffle<C: MutableCollectionType where C.Index.Distance == Int>(var list: C) -> C {
...
}
}
Upvotes: 1