Swift Tips | 小技巧

1、override property | 重写属性

class A {
	var property = false

	private(set) var property2 = false
}

class B: A {
    override var property: Bool {
        get {
            return true
        }
        set {
            super.property = newValue
        }
    }

	override var property2: Bool {
		return true
   } 

2、make a exact duplicate copy of an array

var arr = [1, 2, 3]
var arrCopy = arr.map { $0.copy() }

3、 test equality of Swift enums with associated values

// Before Swift 4.1
enum SimpleToken: Equatable {
    case Name(String)
    case Number(Int)
}

public func ==(lhs: SimpleToken, rhs: SimpleToken) -> Bool {
    switch (lhs, rhs) {
    case let (.Name(a),   .Name(b)),
         let (.Number(a), .Number(b)):
      return a == b
    default:
      return false
    }
}

// Swift 4.1+
enum SimpleToken: Equatable {
    case Name(String)
    case Number(Int)
}

4、获取 GMT+08:00 格式的时区

let localTimeZoneFormatter = DateFormatter()
localTimeZoneFormatter.dateFormat = "ZZZZ"
return localTimeZoneFormatter.string(from: Date())

5、UITabBar 上方添加分割线

if #available(iOS 13.0, *) {
    let appearance = self.tabBar.standardAppearance.copy()
    appearance.shadowImage = .colorForTabBar(color: UIColor(rgb: 0xE2E5F0))
    tabBar.standardAppearance = appearance
} else {
    tabBar.shadowImage = .colorForTabBar(color: UIColor(rgb: 0xE2E5F0))
}

extension UIImage {
    class func colorForTabBar(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 0.5)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context!.setFillColor(color.cgColor)
        context!.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }
}

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

    convenience init(rgb: Int) {
       self.init(
           red: (rgb >> 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }
}

你可能感兴趣的:(#,swift,ios,objective-c,block,swift)