gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:21:16 24 4
gpt4 key购买 nike

你好:)

我正在尝试构建一个自定义类型(结构或类,任何一个都适合),其值可以在我需要时隐式转换为 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 中可能吗?

最佳答案

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), ()
*/

更新扩展字符串怎么样: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

关于swift - 使结构或类可隐式转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com