使结构或类可隐式转换为String

时间:2016-01-09 20:07:36

标签: swift swift2

Bonjour:)

我正在尝试构建一个自定义类型(结构或类,任何适合的),当我需要它时,其值可以隐式转换为String

以下是我正在寻找的一个例子:

public struct IKString {
    private var internalValue: String

    public init(_ value: String) {
        internalValue = value
    }
}

...

let test = IKString("Hello, world!")
myUILabel.text = test // This fails but I'm looking for a way to make it compile

Swift可以吗?

2 个答案:

答案 0 :(得分:4)

class C: CustomStringConvertible {
    let property1: Int; 
    init(i: Int) {
        property1 = i
    }

    var property2: ()->() = { print("some computed property") }
    var description: String {
        return "instance of this class C has two properties: property1: \(property1) and property2: \(property2) whith type \(property2.dynamicType)"
    }
}
let c  = C(i: 100)
let s: String = c.description
print(s) // instance of this class C has two properties: property1: 100 and property2: (Function) whith type () -> ()

看那个

print(c)

给你相同的结果!

var text: String = ""
print(c, toStream: &text)
print(text)

将文本设置为相同的值。顺便说一句

print("\(c.property2), \(c.property2())")
// prints two lines
/*
some computed property
(Function), ()
*/

UPDATE 那么扩展字符串:IKString {...} ??

struct Localisation {}
protocol IKString {
    mutating func foo()
    init(s: String, l: Localisation)
}

extension String: IKString {
    init(s: String, l: Localisation) {
        // some code
        self = s
        foo()
    }
    mutating func foo() {
        self = self.uppercaseString
    } 
}
let s2 = String(s: "blabla",l: Localisation())
print(s2) // BLABLA

答案 1 :(得分:0)

作为CustomStringConvertible一致性解决方案的替代方案(我认为最好是+1!),您可以定义自己的自定义运算符来为您执行转换工作(即访问{{1} } string property)。在此示例中,我将使用前缀运算符通过运算符internalValue在正常StringString赋值之前进行转换。作为替代方案,您可以创建自己的中缀赋值运算符。

=
相关问题