繁体   English   中英

如何在Apple Swift中定义新的“字符串”类型?

[英]How to define a new “String” type in Apple Swift?

我有一些参考字符串,我发布的应用程序构建的参考字符串只是从一项服务接收并传递给另一项服务。 为了进行调试,有必要比较两个参考并将它们打印到控制台。

我的应用程序至少有两种不同类型的参考字符串-两者均不会分配给另一种。

我想在我的代码中有两种独特的类型,称为ArticleReference和ResultReference。

我首先定义了一个“通用”协议,从中可以构建ArticleReference和ResultReference。 让我们在这里处理ArticleReference。

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

如果我接受对'stringLiteral'Xcode的更改,则建议将'stringLiteral'替换为'_'! 无限错误循环。

我是否采取正确的方法? 如果是这样,我哪里出错了?

该错误信息可能会引起误解。 问题是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)
    }
}

添加后,您的代码就可以正确编译。

使用ReferenceType协议的每个结构都需要多个init函数。

public struct ArticleReference:ReferenceType {
    public var value:String
    public init(_ value:String) {
        self.value = value
    }

    public init(stringLiteral value:String) {
        self.value = value
    }

    public init(extendedGraphemeClusterLiteral value:String) {
        self.value = value
    }

    public init(unicodeScalarLiteral value:String) {
       self.value = value
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM