Hi everyone. I’m very new to swift programming and I’ve been building some very, very basic apps. I have a piece of code where a user enters the year of their birth and it returns the Chinese Zodiac of that year. For example, a user enters 1975 - “Year of the Rabbit” is returned.
I’ve created a few arrays, but I have way too many else if statements. Can anyone give me pointers as to how I can drastically reduce this code using other swift methods? Thank you
// My date arrays
let ratArray = [1948, 1960, 1972, 1984, 1996, 2008, 2020]
let oxArray = [1949, 1961, 1973, 1985, 1997, 2009, 2021]
let tigerArray = [1950, 1962, 1974, 1986, 1998, 2010, 2022]
let rabbitArray = [1951, 1963, 1975, 1987, 1999, 2011, 2023]
let dragonArray = [1952, 1964, 1976, 1988, 2000, 2012, 2024]
let snakeArray = [1953, 1965, 1977, 1989, 2001, 2013, 2025]
let horseArray = [1954, 1966, 1978, 1990, 2002, 2014, 2026]
let goatArray = [1955, 1967, 1979, 1991, 2003, 2015, 2027]
let monkeyArray = [1956, 1968, 1980, 1992, 2004, 2016, 2028]
let roosterArray = [1957, 1969, 1981, 1993, 2005, 2017, 2029]
let noInfoArray = [1958, 1959, 1970, 1971, 1982, 1983, 1994, 1995, 2006, 2007, 2018, 2019]
func chineseZodiac(year zodiacYear: Int) → String {
var sign = ""
if ratArray.contains(zodiacYear){
sign = "Year of the Rat"
} else if oxArray.contains(zodiacYear) {
sign = "The Year of the Ox"
} else if tigerArray.contains(zodiacYear) {
sign = "The Year of the Ox"
} else if rabbitArray.contains(zodiacYear) {
sign = "The Year of the Rabbit"
} else if dragonArray.contains(zodiacYear) {
sign = "The Year of the Dragon"
} else if snakeArray.contains(zodiacYear) {
sign = "The Year of the Snake"
} else if horseArray.contains(zodiacYear){
sign = "The Year of the Horse"
} else if goatArray.contains(zodiacYear) {
sign = "The Year of the Goat"
} else if monkeyArray.contains(zodiacYear) {
sign = "The Year of the Monkey"
} else if roosterArray.contains(zodiacYear) {
sign = "The Year of the Rooster"
} else if noInfoArray.contains(zodiacYear) {
sign = "Sorry, no data available for this year"
} else {
sign = "Please choose a year from 1948 - 2029"
}
return sign
}
print(chineseZodiac(year: 1970))