This is what I would write if I were given the PHP class Tag
in your link:
import Foundation
public class MyTag {
public let tag: UInt8
public let value: String
public init(tag: UInt8, value: String) {
self.tag = tag
assert(value.utf8.count < 256, "The length of `value` needs to be less than 256.")
self.value = value
}
public var length: Int {
value.utf8.count
}
///Use this instead of `__toString()`.
///Please remember, in PHP, `__toString()` may be called implicitly in many cases.
///You may need to replace all such cases to use this `getData()` explicitly.
public func getData() -> Data {
return toByteData(tag)
+ toByteData(UInt8(length))
+ value.data(using: .utf8)!
}
///Use this instead of `toHex()`.
func toByteData(_ value: UInt8) -> Data {
return Data([value])
}
}
Generally, it is hard to convert code of some language having a concept of binary string into Swift.
You may have two ways:
- Use
String
and consider how you embed binary data into String
. - Use
Data
and when you need to concatenate it with String
, convert the String
to Data
before concatenating.
I would choose the latter.
let myTag = MyTag(tag: 1, value: "abc")
print(myTag.toByteData(1).base64EncodedString())
//-> AQ==