Search code examples
swiftfoundation

\n automatically add on array Values after converting AnyObject to String?


I am trying to append AnyObject type Values on my arr. but when first i convert AnyObject to String it automatically add \n with every values? I did't want to change arr type and structure. Can anyone please tell me what i do?? Thanks

var arr : [(String, String)] = [("https://www.youtube.com/watch?v=AtKZKl7Bgu0","6.jpg"),
                                  ("https://www.youtube.com/watch?v=4SYlLi5djz0","7.jpg")]

var url : [String] = []
var image : [String] = []

for i in arr{

  url.append(i.0)
  image.append(i.1)
  print("URL values.............. \(url)")
  print("Image values.............. \(image)")
}

NSUserDefaults.standardUserDefaults().setObject(url, forKey: "u")
NSUserDefaults.standardUserDefaults().setObject(image, forKey: "i")
NSUserDefaults.standardUserDefaults().synchronize()

let u = NSUserDefaults.standardUserDefaults().objectForKey("u")! //as! String
let i = NSUserDefaults.standardUserDefaults().objectForKey("i")!

print("U Values   \(u)")
print("I values   \(i)")

// let tup = ("\(u)", "\(i)")
let tup = (String(u),String(i))
print("tup Values \(tup)")
arr.removeAll()
arr.append(tup)
print("arr Values    \(arr)")

Output


Solution

  • print adds the newlines: your objects are unchanged, there's no "\n" added anywhere, this is only in the printed representation.

    It doesn't add the newline when you print the objects after having declared them, because their type is known (String), so print just prints the Strings correctly without having to guess.

    But after you get your values back from NSUserDefaults.standardUserDefaults().objectForKey their type is AnyObject, so print behaves entirely differently.