Skip to content

Instantly share code, notes, and snippets.

@crmitchelmore
Last active May 20, 2016 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crmitchelmore/76569c49c7a82ee06ce957590b9ac924 to your computer and use it in GitHub Desktop.
Save crmitchelmore/76569c49c7a82ee06ce957590b9ac924 to your computer and use it in GitHub Desktop.
Converting strings in to arrays
import Foundation
extension Array: StringLiteralConvertible {
init(string: String) {
self.init()
appendContentsOf(string.componentsSeparatedByString(",").flatMap {
switch Element.self {
case is Int.Type:
return Int($0) as? Element
case is Double.Type, is Float.Type:
return Double($0) as? Element
default:
return $0 as? Element
}
})
}
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
public init(stringLiteral value: StringLiteralType){
self.init(string: value)
}
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType){
self.init(string: value)
}
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType){
self.init(string: value)
}
}
let a: Array<String> = "1,2,3" // ["1", "2", "3"]
let b: Array<Int> = "1,2,3" // [1, 2, 3]
let c: Array<Double> = "1.5,2.0,foo,3.1" // [1.5, 2.0, 3.1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment