如何在Swift UI中从字符串中获取子字符串? [英] How to get substring out of string in swift ui?
本文介绍了如何在Swift UI中从字符串中获取子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在UIKit中,我使用相同的方法从长字符串中仅获取一部分,并且在那里工作.但是,它不能在快速的ui应用程序中工作.我想知道它是否不是字符串,而是其他东西.有谁知道更好的解决方案,只从长文本中获取一个短子字符串?
In UIKit I used the same method to get only one part out of a long string and there it worked. However it dosen't work in swift ui app. I have wondered if it might be that it is not a string, but something else. Does anyone know a better solution to only get a short substring out of the long text?
let url = URL(string: "https://midcdmz.nrel.gov/apps/spa.pl?syear=2020&smonth=1&sday=1&eyear=2020&emonth=1&eday=1&otype=0&step=60&stepunit=1&hr=12&min=0&sec=0&latitude=39.743&longitude=-105.178&timezone=-7.0&elev=1829&press=835&temp=10&dut1=0.0&deltat=64.797&azmrot=180&slope=0&refract=0.5667&field=0")
struct ContentView: View {
var html = try! String(contentsOf: url!, encoding: String.Encoding.ascii)
let leftSideOfTheValue = "1/1/2020,0:00:00,"
let rightSideOfTheValue = "1/1/2020,1:00:00,"
guard let leftRange = html.range(of: leftSideOfTheValue) else {
print("cant find left range")
return
}
guard let rightRange = html.range(of: rightSideOfTheValue) else {
print("cant find right range")
return
let rangeOfTheValue = leftRange.upperBound..<rightRange.lowerBound
let elevationInfo = (html[rangeOfTheValue])
var body: some View {
Text(elevationInfo)
}
推荐答案
可能的解决方案(使用功能):
Possible solution (Using function):
struct ContentView: View {
private let url = URL(string: "https://midcdmz.nrel.gov/apps/spa.pl?syear=2020&smonth=1&sday=1&eyear=2020&emonth=1&eday=1&otype=0&step=60&stepunit=1&hr=12&min=0&sec=0&latitude=39.743&longitude=-105.178&timezone=-7.0&elev=1829&press=835&temp=10&dut1=0.0&deltat=64.797&azmrot=180&slope=0&refract=0.5667&field=0")
var body: some View {
Text(self.getSubstring(from: url))
}
private func getSubstring(from url: URL?) -> String {
guard let url = url else {
return ""
}
let html = try! String(contentsOf: url, encoding: String.Encoding.ascii)
let leftSideOfTheValue = "1/1/2020,0:00:00,"
let rightSideOfTheValue = "1/1/2020,1:00:00,"
guard let leftRange = html.range(of: leftSideOfTheValue) else {
print("cant find left range")
return ""
}
guard let rightRange = html.range(of: rightSideOfTheValue) else {
print("cant find right range")
return ""
}
let rangeOfTheValue = leftRange.upperBound..<rightRange.lowerBound
return String(html[rangeOfTheValue])
}
}
这篇关于如何在Swift UI中从字符串中获取子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文