Swift 类型转换

3,828 阅读2分钟

Swift: CGFloat 为什么不能转换成 Float

Cannot convert value of type 'CGFloat?' to type 'Float' in coercion

原因:

The Float and CGFloat data types sound so similar you might think they were identical, but they aren't: CGFloat is flexible in that its precision adapts to the type of device it's running on, whereas Float is always a fixed precision. Float和CGFloat数据类型听起来很相似,你可能认为它们是相同的,但它们不是:CGFloat的灵活性在于它的精度适应它运行的设备类型,而Float总是一个固定的精度。

所以CGFloat是更加广泛的一种类型,它的兼容性更加好,Float可以转成CGFloat:

var progress:Float = 0.88
var cgFloatValue = CGFloat(progress)

 if progress == CGFloat(1.0) {
 

 }

由于Swift编译器向上兼容特性,在Swift中CGFloat转Float是不被容许的,这一点和访问控制权限很像。

Data相关

Data to Image,Date to Image

    let imgData = UIImage.pngData(self.coverImage?)
    let img = UIImage(data: imgData)

Cannot convert value of type 'Int64?' to expected argument type 'Int'

Int64 to Int

let int64Value: Int64 = 6666888
let intValue = NSNumber(value: int64Value).intValue

String相关

2.1Stirng to URL & URL to String

2.2 String convert to Double/Float

let myString = "666"
let myDouble = (myString as NSString).doubleValue
let myFloat = (myString as NSString).floatValue

2.2 Double/Float/Int convert to String

String("\(doubleValue)")

3.string to NSMutableAttributeString

    let normalStr = prefix + suffix
    let mutableAttributeString = NSMutableAttributedString(string: normalStr)

4. Swift设置字符串NSMutableAttributeString属性:

        let title = "蓝朋友"
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 8),
                                   NSAttributedString.Key.foregroundColor : UIColor.blue]
        let attributeString = NSMutableAttributedString(string: title, attributes: attributes)
        rightBtn.setAttributedTitle(attributeString, for: .normal)

5. 封装NSMutableAttributedString富文本

NSAttributedString.Key.foregroundColor 和 NSAttributedString.Key.font

    func getAttributeStringWith(_ prefix: String, _ suffix: String) -> NSMutableAttributedString {
        let normalStr = prefix + suffix
        let mutableAttributeString = NSMutableAttributedString(string: normalStr)
        //设置prefix attributes属性
        let prefixAttribute = [NSAttributedString.Key.foregroundColor: UIColor.white,
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)] as [NSAttributedString.Key : Any]
        mutableAttributeString.addAttributes(prefixAttribute, range: NSRange.init(location: 0, length: prefix.count))
        //设置suffix attributes属性
        let suffixAttribute = [NSAttributedString.Key.foregroundColor: UIColor.init(red: 252/255.0, green: 46/255.0, blue: 117/255.0, alpha: 1),
                         NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25, weight: .bold)] as [NSAttributedString.Key: Any]
        mutableAttributeString.addAttributes(suffixAttribute, range: NSRange.init(location: prefix.count, length: suffix.count))
        
        return mutableAttributeString
    }

6.KVO 监听属性currentIndex

forKeyPath:@"currentIndex" options:5 context:0x0] was sent to an object that is not KVC-compliant for the "DetailVideoIndex" property.'

原因是KVO需要使用OC runtime动态性。定义如下:

@objc dynamic var currentIndex: NSInteger = 0

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "currentIndex" {
            //do what you want
        }

//Swift数组转json

func getJSONStringFromArray(array:Array<Any>) -> String {
    if (!JSONSerialization.isValidJSONObject(array)) {
        print("无法解析出JSONString")
        return ""
    }
    let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
    let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
    return JSONString! as String
}

//json转数组

func getArrayFromJSONString(jsonString:String) -> Array<Any>{
    let jsonData:Data = jsonString.data(using: .utf8)!
    let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
    if array != nil {
        return array as! Array
    }
    return array as! Array
}