我正在try 更新我的应用程序以使用Oslog(Logger). 我目前使用的系统允许我使用简单的字符串插值,我也期望Oslog也会如此,但我在一个简单的测试中看到了所有类型的错误:
import SwiftUI
import OSLog
extension Logger {
static let statistics = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "NS")
}
struct MyCustom: CustomStringConvertible {
let description = "My Custom description"
}
struct MyDebug: CustomDebugStringConvertible {
let debugDescription = "My Debug description"
}
struct NoneOfTheAbove {
var defaultValue = false
}
struct Person: Identifiable {
let id = UUID()
let index: Int
let name: String
let age: Int
static let maxNameLength = 15
}
@main
struct OggTstApp: App {
let myCustom = MyCustom()
let myDebug = MyDebug()
let noneOfTheAbove = NoneOfTheAbove()
var optionalCustom: MyCustom?
var optionalDebug: MyDebug? = MyDebug()
init() {
print("init")
Logger.statistics.debug("debug init")
}
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
testLogs()
}
}
}
func testLogs() {
print("structs")
Logger.statistics.error("\(myCustom)")
// Logger.statistics.error("This is a test: \(myDebug)") // Type of expression is ambiguous without a type annotation
let string = "\(myDebug)"
Logger.statistics.error("\(string)")
// Logger.statistics.error(noneOfTheAbove) // Cannot convert value of type 'NoneOfTheAbove' to expected argument type 'OSLogMessage'
// Logger.statistics.error("\(noneOfTheAbove)") // Type of expression is ambiguous without a type annotation
let noneOTA = "\(noneOfTheAbove)"
// Logger.statistics.error(noneOTA) // Cannot convert value of type 'String' to expected argument type 'OSLogMessage'
Logger.statistics.error("\(noneOTA)")
// Logger.statistics.warning(optionalCustom) // Cannot convert value of type 'MyCustom?' to expected argument type 'OSLogMessage'
let optCust = "\(optionalCustom)" // Warning
Logger.statistics.warning("\(optCust)")
// Logger.statistics.log("Optional not nil: \(optionalDebug)") // No exact matches in call to instance method 'appendInterpolation'
let optNotNil = "\(optionalDebug)" // Warning
Logger.statistics.log("\(optNotNil)")
let aPerson = Person(index: 2, name: "George", age: 21)
let people = [aPerson]
people.forEach {
testLog($0)
}
}
func testLog(_ person: Person) {
Logger.statistics.debug("\(person.index) \(person.name) \(person.id) \(person.age)")
// Logger.statistics.debug("\(person.index) \(person.name, align: .left(columns: Person.maxNameLength)) \(person.id) \(person.age, format: .fixed(precision: 2))") // No exact matches in call to instance method 'appendInterpolation'
}
}
董说双弦插值才能发挥作用,感觉真的很痛苦. 这些警告是意料之中的,尽管我希望我能写一些扩展来让它们消失,但目前我的重点是错误.
我做错了什么吗?这有什么技巧吗? 顺便说一句,我只在控制台中使用这些日志(log),我不太关心能否检索它们(我可以将内插字符串值保持为私有,以防万一).