String个人总结

let priceString = NSMutableAttributedString.init(string: "¥\(productModel?.salePrice ?? 0)") priceString.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 28, weight: .semibold)~], range: NSRange.init(location: 1, length: priceString.length - 1)) cell?.priceLabel.attributedText = priceString

一、基础
1.字符串替换 let value2 = value.replacingOccurrences(of: "; ", with: "")

二、String与其他类型的相互转换 【String个人总结】
let str = "I am FlyElephant" let array = str.components(separatedBy:" ")let data = https://www.it610.com/article/[1, 2, 3, 4, 5] let dataStr = data.map(String.init) let result = dataStr.joined(separator:",")


let string = url.absoluteString let url = URL(string: urlSting)


// Double转String,7位小数 let strVar = String.init(format: "%\(8)f° E%\(8)f° N", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)


let data = "https://www.it610.com/article/你好".data(using: String.defaultCStringEncoding) let bytes = [UInt8](data)let data = https://www.it610.com/article/Data(bytes: bytes, count: bytes.count) let typeString = data.string(encoding: .utf8) ??""


if let dataFromString = result?.data(using: .utf8, allowLossyConversion: false) { let json = try? JSON(data: dataFromString) ddPrint(json)guard let jsons = json else { return }let data = https://www.it610.com/article/try? jsons.rawData() guard let dataTemp = data else { return } let decoder = JSONDecoder() do { let obj = try decoder.decode(LastResult.self, from: dataTemp) self.logisticsModel = obj self.table.reloadData() } catch { ddPrint("数据转化错误\(error)") }}

三、计算文字宽度 // 动态计算Label宽度
func getLabelWidth(str: String, font: UIFont, height: CGFloat)-> CGFloat { let statusLabelText: NSString = str as NSString let size = CGSize(width: CGFloat(MAXFLOAT), height: height) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil).size return strSize.width }

您应该已经知道可以检查字符串是否包含单个单词,如下所示: let string = "The rain in Spain" let stringResult = string.contains("rain")您还应该知道可以检查字符串数组以查看特定字符串是否在那里,如下所示: let words = ["clouds", "rain", "wind"] let arrayResult = words.contains("rain")好吧,这两个contains()方法可以组合在一起形成一个新的含义:”这个数组中的任何单词都存在于这个字符串中吗?”,如下所示: let combinedResult = words.contains(where: string.contains)

    推荐阅读