如何在SwiftUI中创建通用首选项键?
我想制作一个通用首选项键,我的代码有两个问题 首先,我需要为T定义(),使用正常类型,如String,Int作为String()或Int(),因此我需要为T定义成员初始值设定项 第二个Xcode抱怨我的首选项键不符合equalable,而我这样做了 如何解决这两个问题?谢谢如何在SwiftUI中创建通用首选项键?,swift,swiftui,Swift,Swiftui,我想制作一个通用首选项键,我的代码有两个问题 首先,我需要为T定义(),使用正常类型,如String,Int作为String()或Int(),因此我需要为T定义成员初始值设定项 第二个Xcode抱怨我的首选项键不符合equalable,而我这样做了 如何解决这两个问题?谢谢 struct CustomPreferenceKey:PreferenceKey{ 静态var defaultValue:T{get{return T()} 静态函数reduce(值:inout T,nextValue:
struct CustomPreferenceKey:PreferenceKey{
静态var defaultValue:T{get{return T()}
静态函数reduce(值:inout T,nextValue:()->T){value=nextValue()}
}
以下是一种可能的移动方法。使用Xcode 12.4/iOS 14.4进行测试
protocol Initable {
init()
}
extension String: Initable {
}
struct CustomPreferenceKey<T: Equatable & Initable>: PreferenceKey {
typealias Value = T
static var defaultValue: T { get { T() } }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
struct ContentView: View {
@State private var stringOfText: String = "Hello, world!"
var body: some View {
Text(stringOfText)
.preference(key: CustomPreferenceKey<String>.self, value: stringOfText)
.onPreferenceChange(CustomPreferenceKey<String>.self) { newValue in print(newValue) }
}
}
协议可初始化{
init()
}
扩展字符串:Initable{
}
结构CustomPreferenceKey:PreferenceKey{
类型别名值=T
静态var defaultValue:T{get{T()}
静态func REDUCT(值:inout值,nextValue:()->值){
value=nextValue()
}
}
结构ContentView:View{
@国家私有var stringOfText:String=“你好,世界!”
var body:一些观点{
文本(stringOfText)
.preference(键:CustomPreferenceKey.self,值:stringOfText)
.onPreferenceChange(CustomPreferenceKey.self){newValue in print(newValue)}
}
}
为什么我们需要typealias Value=T?它甚至可以与T一起工作,而不使用Value
struct CustomPreferenceKey<T: Equatable>: PreferenceKey {
static var defaultValue: T { get { return T() } }
static func reduce(value: inout T, nextValue: () -> T) { value = nextValue() }
}
protocol Initable {
init()
}
extension String: Initable {
}
struct CustomPreferenceKey<T: Equatable & Initable>: PreferenceKey {
typealias Value = T
static var defaultValue: T { get { T() } }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
struct ContentView: View {
@State private var stringOfText: String = "Hello, world!"
var body: some View {
Text(stringOfText)
.preference(key: CustomPreferenceKey<String>.self, value: stringOfText)
.onPreferenceChange(CustomPreferenceKey<String>.self) { newValue in print(newValue) }
}
}