Swift一些处理方法(ChatGPT)

本文提供了几个Swift函数,用于根据固定宽度计算字符串的高度,以及根据固定高度计算字符串的宽度。还介绍了判断Double小数点后数值的方法,以及处理UITextField输入限制。此外,文章涵盖了数据在String与Data之间的转换,并展示了Int8与UInt8之间的互转操作。
摘要由CSDN通过智能技术生成

ChatGPT回答的

1. 字符串根据固定宽度计算高度或根据固定高度计算宽度

  1. 根据宽度计算高度
func getHeight(for text: String, withFixedWidth width: CGFloat, font: UIFont, lineSpacing: CGFloat) -> CGFloat {
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpacing
    
    let attributes: [NSAttributedString.Key: Any] = [.font: font, .paragraphStyle: paragraphStyle]
    let attributedText = NSAttributedString(string: text, attributes: attributes)
    
    let boundingRect = attributedText.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
    
    return ceil(boundingRect.height)
}

  1. 根据高度计算宽度
func getWidth(for text: String, withHeight height: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
    let boundingRect = text.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: font], context: nil)
    return ceil(boundingRect.width)
}

2. swift 判断一个Double的小数点后面的数是否大于0

let myDouble = 3.14159265359
let myString = String(myDouble)

if let decimalIndex = myString.firstIndex(of: ".") {
    let decimalPart = myString[decimalIndex...]
    if let decimalValue = Double(decimalPart), decimalValue > 0 {
        print("Decimal value is greater than 0: \(decimalValue)")
    } else {
        print("Decimal value is not greater than 0 or could not be converted to a Double")
    }
} else {
    print("No decimal point found in string")
}

  1. 键盘连续输入三次小数点,前面的数字会变为三个点,解决方案
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let updatedText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? ""
        
        let dotCount = updatedText.components(separatedBy: ".").count - 1
        
        if string == "." && dotCount >= 2 {
            return false // 阻止输入第三个小数点
        }
        
        return true
    }

3. data转String

import Foundation

class DataTool {
    static func stringToNSData(srcString: String) -> Data? {
        let bytes = srcString.components(separatedBy: ":")
        
        let data = bytes.compactMap { byte in
            return UInt8(byte, radix: 16)
        }
        
        return Data(data)
    }
    
    static func nsDataToArray(srcData: Data) -> [String] {
        let bytes = [UInt8](srcData)
        
        let hexStrings = bytes.map { byte in
            return String(format: "%02X", byte)
        }
        
        // 在字符串数组中的每个元素之间插入冒号
        let result = stride(from: 0, to: hexStrings.count, by: 2).map { index in
            return hexStrings[index] + hexStrings[index + 1]
        }.joined(separator: ":")
        
        return [result]
    }
}

let macString = "AA:BB:CC:DD:EE:FF"
let macData = DataTool.stringToNSData(srcString: macString)
print("【测试转换】转换前字符串:\(macString)")
let changeString = DataTool.nsDataToArray(srcData: macData ?? Data())
print("【测试转换】转换后字符串:\(changeString)")

4. Int8 和 UInt8互转

// 1. OC写法,把UInt8转Int8
NSMutableArray<NSNumber *> *arr = [NSMutableArray array];
for (NSNumber *element in srcArr) {
    int8_t temp = (int8_t)[element unsignedCharValue];
    [arr addObject:@(temp)];
}
// 2. swift写法,把UInt8转Int8
var arr = [Int8]()
for element in srcArr {
    let temp = numericCast(element)
    let newE = Int8(bitPattern: temp)
    arr.append(newE)
}

// 3. OC写法,把Int8转UInt8
NSMutableArray<NSNumber *> *arr = [NSMutableArray array];
for (NSNumber *element in tempArr) {
    NSUInteger temp = [element unsignedIntegerValue] & 0xFF;
    NSNumber *newE = @(temp);
    [arr addObject:newE];
}

// 4. swift写法,把Int8转UInt8
var arr = [UInt8]()
for element in tempArr {
    let temp = element.uintValue & 0xFF
    let newE = UInt8(temp)
    arr.append(newE)
}
// 5. 取值范围为0~255的Int转为Int8后,再转为Int
arr = arr.map { Int(Int8(bitPattern: UInt8($0)))}
// 转换前:[152, 0, 0, 129, 209, 177]
// 转换后:[-104, 0, 0, -127, -47, -79]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Swift中的enum是一种用来定义一组相关值的数据类型。通过使用enum关键字,我们可以创建一个枚举类型,并在其中定义多个成员。每个成员可以表示一个特定的值或者一个相关的选项。 在Swift中,我们可以使用enum关键字来声明一个枚举,并在其中定义成员。例如,我们可以通过下面的代码声明一个名为LGEnum的枚举,并定义了三个成员test_one、test_two和test_three: enum LGEnum { case test_one case test_two case test_three } 通过使用枚举,我们可以在代码中以简洁而清晰的方式表示一组相关的选项或者状态。我们可以使用switch语句来根据枚举成员的不同进行流程控制。这种用法在处理多个不同的情况时非常有用。 此外,在Swift中的枚举还可以附带原始值。原始值是在定义枚举时为每个成员指定的固定值。原始值可以是字符串、字符、整数或者浮点数。通过在定义枚举时使用冒号和原始值类型来指定原始值。例如,我们可以定义一个名为Color的枚举,并为每个成员指定一个字符串值: enum Color : String { case red = "Red" case amber = "Amber" case green = "Green" } 此外,我们还可以为枚举成员指定关联值,这些关联值可以是任意类型的值。这使得枚举在表示复杂的数据结构时非常灵活和强大。 总之,Swift中的enum关键字允许我们创建和使用枚举类型,以便在代码中表示一组相关的选项或者状态。枚举可以带有原始值,使得我们可以更灵活地对枚举成员进行操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Swift —— Enum & optional](https://blog.csdn.net/LinShunIos/article/details/122404674)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [详解Swift中enum枚举类型的用法](https://download.csdn.net/download/weixin_38587130/12796285)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值