我有一个包含2个数组的数组A:
[[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday], [Monday, Wednesday]]
现在我想用以下代码替换数组A的元素:
[[Sun, Mon, Tue, Wed, Thu, Fri, Sat], [Mon, Wed]]
为此,我打算使用:
for days in operatingDays {
for weekdays in days
{
if (operatingDays[i] as? String == "Sun") {
operatingDays[i] = "Su"
} else if operatingDays[i] as? String == "Mon"{
operatingDays[i] = "Mo"
} else if operatingDays[i] as? String == "Tue"{
operatingDays[i] = "Tu"
} else if operatingDays[i] as? String == "Wed"{
operatingDays[i] = "We"
} else if operatingDays[i] as? String == "Thu"{
operatingDays[i] = "Th"
} else if operatingDays[i] as? String == "Fri"{
operatingDays[i] = "Fr"
} else if operatingDays[i] as? String == "Sat"{
operatingDays[i] = "Sa"
}
}
}
答案 0 :(得分:3)
var input = [["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], ["Monday", "Wednesday"]]
var output = [[String]]()
for array in input {
output.append(array.map {String($0.characters.prefix(3))})
}
输出将包含[["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], ["Mon", "Wed"]]
答案 1 :(得分:2)
将operatingDays
视为更具体的内容
for days in operatingDays as! [[String]]
答案 2 :(得分:1)
您可以使用AnyObject
类型来投射数组,例如此代码可以帮助您:
var array: [AnyObject] = [[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday], [Monday, Wednesday]]
array = [[Sun, Mon, Tue, Wed, Thu, Fri, Sat], [Mon, Wed]]
现在,如果你想做一些特别的事情,你必须施放那个数组:
if let item = array[2] as? String{
print(item)
}
或者您只需打印阵列:
for item in array{
print("my item is \(item)")
}
答案 3 :(得分:1)
尝试使用此功能,正如我所说,您需要将日期设为[String]
for days in operatingDays {
if let daysArray = days as? [String]
{
for weekdays in daysArray
{
operatingDays[i] =
if (operatingDays[i] as? String == "Sun") {
operatingDays[i] = "Su"
} else if operatingDays[i] as? String == "Mon"{
operatingDays[i] = "Mo"
} else if operatingDays[i] as? String == "Tue"{
operatingDays[i] = "Tu"
} else if operatingDays[i] as? String == "Wed"{
operatingDays[i] = "We"
} else if operatingDays[i] as? String == "Thu"{
operatingDays[i] = "Th"
} else if operatingDays[i] as? String == "Fri"{
operatingDays[i] = "Fr"
} else if operatingDays[i] as? String == "Sat"{
operatingDays[i] = "Sa"
}
}
}
}
希望这有帮助