LoginSignup
5
4

More than 5 years have passed since last update.

【Swift】2つの配列を交互につなぎ合わせる

Last updated at Posted at 2015-08-16

Swift 3


let num = 1234

// Int -> [String]
let numList = String(num).characters.flatMap { String($0) }
print(numList)
// ["1", "2", "3", "4"]

let opeList = ["+", "-", "*"]
let zipped = zip(numList, opeList + [""]) // 要素数を合わせる
print(zipped)
// Zip2Sequence<Array<String>, Array<String>>(_sequence1: ["1", "2", "3", "4"], _sequence2: ["+", "-", "*", ""])

let equation = zipped.reduce("") { $0 + $1.0 + $1.1 }
print(equation)
// "1+2-3*4"

or


let num = 1234

// Int -> [String]
let numList = String(num).characters.flatMap { String($0) }
print(numList)
// ["1", "2", "3", "4"]

let opeList = ["+", "-", "*"]
let zipped = zip(numList, opeList + [""])
print(zipped)
// Zip2Sequence<Array<String>, Array<String>>(_sequence1: ["1", "2", "3", "4"], _sequence2: ["+", "-", "*", ""])

let concatenated = zipped.map { $0.0 + $0.1 }
print(concatenated)
// ["1+", "2-", "3*", "4"]

let equation = concatenated.joined()
print(equation)
// "1+2-3*4"

Swift 2


let num = 1234

// Int -> [String]
let numList = String(num).characters.flatMap { String($0) }
print(numList)
// ["1", "2", "3", "4"]

let opeList = ["+", "-", "*"]
let zipped = zip(numList, opeList + [""]) // 要素数を合わせる
print(zipped)
// Zip2Sequence<Array<String>, Array<String>>(_sequences: (["1", "2", "3", "4"], ["+", "-", "*", ""]))

let equation = zipped.reduce("") { $0 + $1.0 + $1.1 }
print(equation)
// "1+2-3*4"

or


let num = 1234

// Int -> [String]
let numList = String(num).characters.flatMap { String($0) }
print(numList)
// ["1", "2", "3", "4"]

let opeList = ["+", "-", "*"]
let zipped = zip(numList, opeList + [""])
print(zipped)
// Zip2Sequence<Array<String>, Array<String>>(_sequences: (["1", "2", "3", "4"], ["+", "-", "*", ""]))

let concatenated = zipped.map { $0.0 + $0.1 }
print(concatenated)
// ["1+", "2-", "3*", "4"]

let equation = "".join(concatenated)
print(equation)
// "1+2-3*4"
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4