I need to localize the name oft tabbar and have this in a enum
import Foundation
import SwiftUI
enum TabBarItem: Hashable {
case home, favorites, profile, messeges, impress
var iconName: String {
switch self {
case .home: return "house"
case .favorites: return "heart"
case .profile: return "person"
case .messeges: return "message"
case .impress: return "gear"
}
}
var title: String {
switch self {
case .home: return "Home"
case .favorites: return "Favorite"
case .profile: return "Profile"
case .messeges: return "Messages"
case .impress: return localizedString(value: "ImpressTabTitle")
}
}
var color: Color {
switch self {
case .home: return Color.red
case .favorites: return Color.blue
case .profile: return Color.green
case .messeges: return Color.orange
case .impress: return Color.purple
}
}
func localizedString(value: String) -> String {
let returnvalue: String = LocalizedStringKey("ImpressTabTitle")
return returnvalue
}
}
But I get always the error:
Cannot convert return expression of type 'Text' to return type 'String'
Where is my missunderstanding of this?
The string in the localizationfile works, when i use it direkt in a view
"ImpressTabTitle" = "Impress";
CodePudding user response:
I think your question lacks something, because the code you show generates another error: cannot convert value of type 'LocalizedStringKey' to specified type 'String'
. The error is pretty straightforward – you try to return LocalizedStringKey
, whereas the method is declared to return String
.
I suppose you're going to use it in your SwiftUI views, right? If so, you can just change your return to LocalizedStringKey
and pass it to your SwiftUI views directly, as if it were a string literal:
import SwiftUI
enum TabBarItem: Hashable {
case home
case favorites
func localizedTitle() -> LocalizedStringKey {
switch self {
case .home:
return LocalizedStringKey("HomeTabTitle")
case .favorites:
return LocalizedStringKey("FavoritesTabTitle")
}
}
}
// SwiftUI usage example.
Text(TabBarItem.home.localizedTitle())