我有一些引用字符串,我的应用在发布版本中只是从一个服务接收并传递给另一个服务。为了进行调试,需要比较两个引用并将它们打印到控制台。
我的应用程序至少有两种不同类型的引用字符串-两者都不能分配给另一个。
我希望代码中有两种唯一的类型,称为articlerence和ResultReference。
我首先定义了一个“通用”协议,从中可以构建articlerence和ResultReference。让我们在这里处理文章参考。
public protocol ReferenceType: Comparable, StringLiteralConvertible {
var value:String {set get}
init(_ value:String)
}
public func + <T :ReferenceType> (lhs:T, rhs:T) -> T {
return T(lhs.value + rhs.value)
}
public func += <T :ReferenceType> (inout lhs:T, rhs:T) -> T {
lhs.value += rhs.value
}
public func == <T :ReferenceType> (lhs:T, rhs:T) -> Bool {
return lhs.value == rhs.value
}
public func < <T :ReferenceType> (lhs:T, rhs:T) -> Bool {
return lhs.value < rhs.value
}
public func > <T :ReferenceType> (lhs:T, rhs:T) -> Bool {
return lhs.value > rhs.value
}
这是一个引用类型。
public struct ArticleReference :ReferenceType {
public var value:String
public init(_ value:String) {
self.value = value
}
}
Xcode 6.4抱怨ArticleReference。
public init(_ value:String) {
错误:初始值设定项“init”的参数与协议“StringLiteralConvertible”所需的参数不同(“init(stringLiteral:);)
并提出用stringLiteral替换'uu'
如果我接受对'stringLiteral'Xcode的更改,则建议将'stringLiteral'替换为'uu'!无限错误循环。
我是不是采取了正确的方法?如果是的话,我哪里做错了?
最佳答案
错误消息可能会误导您。问题是protocol ReferenceType
继承自StringLiteralConvertible
,但是
没有为您的struct ArticleReference
实现所需的方法。
一个可能的实现可能是
extension ArticleReference: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
添加可以使代码编译时没有错误。
关于string - 如何在Apple Swift中定义新的“字符串”类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31774368/