Last active
May 20, 2016 09:31
-
-
Save crmitchelmore/76569c49c7a82ee06ce957590b9ac924 to your computer and use it in GitHub Desktop.
Converting strings in to arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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