Skip to content

Instantly share code, notes, and snippets.

@unnamedd
Last active February 21, 2018 17:51
Show Gist options
  • Save unnamedd/e5c41ce960cae61e724d3f7ff854378d to your computer and use it in GitHub Desktop.
Save unnamedd/e5c41ce960cae61e724d3f7ff854378d to your computer and use it in GitHub Desktop.
[Swift] Using different structs into Enum
public struct Type {
var id: Int
var name: String
var description: String
public init(id: Int, name: String? = nil, description: String? = nil) {
self.id = id
self.name = name ?? ""
self.description = description ?? ""
}
public init(id: Int) {
self.id = id
self.name = ""
self.description = ""
}
}
public enum TypeContact {
case github
case facebook
case twitter
case linkedin
case website
}
extension TypeContact: RawRepresentable {
public typealias RawValue = Type
public init?(_ type: TypeContact) {
self = type
}
public init?(rawValue: RawValue) {
switch rawValue.id {
case 0:
self = .github
case 1:
self = .facebook
case 2:
self = .twitter
case 3:
self = .linkedin
case 4:
self = .website
default:
return nil
}
}
public var rawValue: RawValue {
switch self {
case .github:
return Type(id: 0, name: "github", description: "GitHub")
case .facebook:
return Type(id: 1, name: "facebook", description: "Facebook")
case .twitter:
return Type(id: 2, name: "twitter", description: "Twitter")
case .linkedin:
return Type(id: 3, name: "linkedin", description: "LinkedIn")
case .website:
return Type(id: 4, name: "website", description: "Website")
}
}
}
public struct Contact: CustomStringConvertible {
public let type : TypeContact
public let value: String
public var description: String {
return "<\(self.type.rawValue.description): \(value)>"
}
}
// Mode One
if let type = TypeContact(rawValue: Type(id: 2)) {
let contact = Contact(type: type, value: "tholanda")
print(contact)
}
// Mode Two
if let type = TypeContact(.github) {
let contact = Contact(type: type, value: "unnamedd")
print(contact)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment