简体   繁体   中英

How to represent special characters in String literals in Swift 3

I am new to Swift and I am currently reading the "Swift Programming: The Big Nerd Ranch Guide." I came across a challenge that wants me to create a dictionary that represents a state. My dictionary's keys refer to 3 countries. Each key maps onto an array that holds five of the zip codes within that country. I was allowed to make up the country name and zip codes. The result should match the following:

   Georgia has the following zip codes: [30306, 30307, 30308, 30309, 30310,

                                  30311, 30312, 30313, 30314, 30315,

                                  30301, 30302, 30303, 30304, 30305]

I was able to get the result as he requested but I wasn't able to get the same format, in my code the results appears in the same line like this:

Georgia has the following zip codes: [30306, 30307, 30308, 30309, 30310,30311, 30312, 30313, 30314, 30315, 30301, 30302, 30303, 30304, 30305]

and here is my code:

      var georgia = ["c1" : [30306, 30307, 30308, 30309, 30310] , "c2" : [30311, 30312, 30313, 30314, 30315 ] , "c3" : [30301, 30302, 30303, 30304, 30305] ]
      var resultArray : [Int] = []
      for zipCodes in georgia.values
      {
        for zip in zipCodes
        {
          resultArray.append(zip)
        }
      }
      print("Georgia has the following zip codes :" , resultArray)   

I have been trying to figure out how to match the formatting above as he wants me to, but I wasn't able to get the idea. Any help would be much appreciated.

Just for fun:

let georgia = ["c1" : [30306, 30307, 30308, 30309, 30310] , "c2" : [30311, 30312, 30313, 30314, 30315 ] , "c3" : [30301, 30302, 30303, 30304, 30305] ]

var resultArray = [String]()
for key in georgia.keys.sorted()
{
    let zipCodes = georgia[key]!
    let zipString = zipCodes.map(String.init).joined(separator: ", ")
    resultArray.append(zipString)
}
print("Georgia has the following zip codes : [" + resultArray.joined(separator: ",\n\n\t\t\t\t\t") + "]")

It maps each Int array to String array and joins the items with the ", " separator to a string. The resulting array is also joined with a comma and a couple of new line and tab characters. Finally the brackets are added manually .

But I can't imagine that this is the actual challenge...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM