I confess feeling little stupid, but after hours of trying I have to ask:
class AGE {
static func getAge() -> Int {
var age: Int
for items in dataArray {
if items.name == "Steven" {
age = items.age
}
else {
age = 0
}
}
// variable "age" used before being initialized - WHY?
return age
}
}
I even tried to set var age: Int = 0 at the beginning, but then the function return 0. I hope someone could forgive me this basic question at this point. Any help appreciated.
To make it more clear how dataArray looks like:
struct Person {
let name: String
let lastName: String
let age: Int
}
let person1: Person = Person(name: "Steven", lastName: "miller", age: 23)
let person2: Person = Person(name: "jana", lastName: "drexler", age: 31)
let person3: Person = Person(name: "hanna", lastName: "montana", age: 56)
var dataArray = [Person]()
dataArray.append(person1)
dataArray.append(person2)
dataArray.append(person3)
Update
Trying to assemble the essence of all answers, the solution has to look like this: class AGE {
static func getAge() ->Int {
var age: Int = 0
for items in dataArray {
while items.firstName == "Steven" {
age = items.age
return age
break // This break will never be executed because of return.
}
break // setting the break here, the loop will break after first round
}
return age
}
}
This code works, (with the second break) but only for the first loop. The question remaining is, how to set up return and break after the loop hits its target. Either return or break will prevent the other step.
dataArray?ageoptional, returningnilin the case wheredataArrayis empty. As in such a case, the answer to "what's the age?" is probably not "just been created", rather it's "there is no age".