repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
brendancboyle/SecTalk-iOS | refs/heads/master | PaidyCheckoutSample/Pods/CryptoSwift/CryptoSwift/IntExtension.swift | mit | 4 | //
// IntExtension.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 12/08/14.
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
import Foundation
/* array of bits */
extension Int {
init(bits: [Bit]) {
self.init(bitPattern: integerFromBitsArray(bits) as UInt)
}
}
/* array of bytes */
extension Int {
/** Array of bytes with optional padding (little-endian) */
public func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
public static func withBytes(bytes: ArraySlice<UInt8>) -> Int {
return Int.withBytes(Array(bytes))
}
/** Int with array bytes (little-endian) */
public static func withBytes(bytes: [UInt8]) -> Int {
return integerWithBytes(bytes)
}
}
/** Shift bits */
extension Int {
/** Shift bits to the left. All bits are shifted (including sign bit) */
private mutating func shiftLeft(count: Int) -> Int {
self = CryptoSwift.shiftLeft(self, count)
return self
}
/** Shift bits to the right. All bits are shifted (including sign bit) */
private mutating func shiftRight(count: Int) -> Int {
if (self == 0) {
return self;
}
var bitsCount = sizeofValue(self) * 8
if (count >= bitsCount) {
return 0
}
var maxBitsForValue = Int(floor(log2(Double(self)) + 1))
var shiftCount = Swift.min(count, maxBitsForValue - 1)
var shiftedValue:Int = 0;
for bitIdx in 0..<bitsCount {
// if bit is set then copy to result and shift left 1
var bit = 1 << bitIdx
if ((self & bit) == bit) {
shiftedValue = shiftedValue | (bit >> shiftCount)
}
}
self = Int(shiftedValue)
return self
}
}
// Left operator
/** shift left and assign with bits truncation */
public func &<<= (inout lhs: Int, rhs: Int) {
lhs.shiftLeft(rhs)
}
/** shift left with bits truncation */
public func &<< (lhs: Int, rhs: Int) -> Int {
var l = lhs;
l.shiftLeft(rhs)
return l
}
// Right operator
/** shift right and assign with bits truncation */
func &>>= (inout lhs: Int, rhs: Int) {
lhs.shiftRight(rhs)
}
/** shift right and assign with bits truncation */
func &>> (lhs: Int, rhs: Int) -> Int {
var l = lhs;
l.shiftRight(rhs)
return l
}
| e3f3f2ffc12dc3bf4478affb982a7fc9 | 29.296296 | 217 | 0.634474 | false | false | false | false |
luosheng/OpenSim | refs/heads/master | OpenSim/DeviceManager.swift | mit | 1 | //
// DeviceMapping.swift
// SimPholders
//
// Created by Luo Sheng on 11/9/15.
// Copyright © 2015 Luo Sheng. All rights reserved.
//
import Foundation
final class DeviceManager {
static let devicesKey = "DefaultDevices"
static let deviceRuntimePrefix = "com.apple.CoreSimulator.SimRuntime"
static let defaultManager = DeviceManager()
var runtimes = [Runtime]()
func reload(callback: @escaping ([Runtime]) -> ()) {
SimulatorController.listDevices { (runtimes) in
self.runtimes = runtimes
callback(runtimes)
}
}
}
| 3814b874729e1dc62b24e0223423ea0d | 22.230769 | 73 | 0.637417 | false | false | false | false |
djq993452611/YiYuDaoJia_Swift | refs/heads/master | YiYuDaoJia/YiYuDaoJia/Classes/Tools/Vendor/YLCycleView/YLMenuView/YLMenuView.swift | mit | 1 | //
// YLMenuView.swift
// 斗鱼
//
// Created by shuogao on 2016/11/8.
// Copyright © 2016年 Yulu Zhang. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
//代理
protocol YLMenuViewDelegate : class {
func menuView(_ menuView : YLMenuView, selectedPage: Int, indexInPage index: Int, indexInAllData : Int)
}
class YLMenuView: UIView {
//MARK: -- 定义属性
weak var delegate : YLMenuViewDelegate?
@IBOutlet var pageControl: UIPageControl!
@IBOutlet var collectionView: UICollectionView!
var imageArray : [String]? = nil {
didSet {
collectionView.reloadData()
}
}
var titleArray : [String]? = nil {
didSet {
collectionView.reloadData()
}
}
var itemsOfPage : Int = 8 {//每页几个item
didSet {
collectionView.reloadData()
}
}
var imageViewSize : CGSize = CGSize(width: 48, height: 48) {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
//让空间不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
collectionView.register(UINib.init(nibName: "YLMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
deinit {
print("YLMenuView销毁了")
}
override func layoutSubviews() {
super.layoutSubviews()
//重新设置布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
//MARK: xib创建的类方法
extension YLMenuView {
class func ylMenuView() -> YLMenuView {
return Bundle.main.loadNibNamed("YLMenuView", owner: nil, options: nil)?.first as! YLMenuView
}
}
//MARK: UICollectionViewDataSource
extension YLMenuView : UICollectionViewDataSource, YLMenuViewCellDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if imageArray == nil {
return 0
}
//计算有多少页的算法
let pageNum = (imageArray!.count - 1) / itemsOfPage + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! YLMenuViewCell
cell.delegate = self
setupCelldataWithCell(cell: cell, indexPath: indexPath)
cell.itemsOfPage = self.itemsOfPage
cell.imageViewSize = self.imageViewSize
return cell
}
private func setupCelldataWithCell(cell : YLMenuViewCell, indexPath : IndexPath) {
//0页 0--7
//1页 8--15
//2页 16--23
//取出起点位置
let startIndex = indexPath.item * itemsOfPage
//终点位置
var endIndex = (indexPath.item + 1) * itemsOfPage - 1
//判断越界问题
if endIndex > imageArray!.count - 1 {
endIndex = imageArray!.count - 1
}
//取出每一页的子cell数据,并且赋值给cell
cell.imageArray = Array(imageArray![startIndex...endIndex])
cell.titleArray = Array(titleArray![startIndex...endIndex])
}
func menuViewCell(_ menuViewCell : YLMenuViewCell, selectedIndex index : Int) {
//为了便于数组计算这里的数字起算从0开始。也就是第八个数据实际上是第九个。array[8].取出的是第九个元素
self.delegate?.menuView(self, selectedPage: pageControl.currentPage, indexInPage: index, indexInAllData: pageControl.currentPage * itemsOfPage + index)
print("当前点击的页数下标是:\(pageControl.currentPage),页数中item下标是:\(index),它在总数组的下标是:\(pageControl.currentPage * itemsOfPage + index)")
}
}
//MARK: -- UICollectionViewDelegate
extension YLMenuView : UICollectionViewDelegate {
//设置page的变化
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| 9a4e8e41b40a73ce7db1d2d08be755cc | 30.125984 | 159 | 0.66127 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/StickerShimmerEffectView.swift | gpl-2.0 | 1 | import TGUIKit
import Foundation
private let decodingMap: [String] = ["A", "A", "C", "A", "A", "A", "A", "H", "A", "A", "A", "L", "M", "A", "A", "A", "Q", "A", "S", "T", "A", "V", "A", "A", "A", "Z", "a", "a", "c", "a", "a", "a", "a", "h", "a", "a", "a", "l", "m", "a", "a", "a", "q", "a", "s", "t", "a", "v", "a", ".", "a", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", ","]
private func decodeStickerThumbnailData(_ data: Data) -> String {
var string = "M"
data.forEach { byte in
if byte >= 128 + 64 {
string.append(decodingMap[Int(byte) - 128 - 64])
} else {
if byte >= 128 {
string.append(",")
} else if byte >= 64 {
string.append("-")
}
string.append("\(byte & 63)")
}
}
string.append("z")
return string
}
class StickerShimmerEffectView: View {
private let backgroundView: View
private let effectView: ShimmerEffectForegroundView
private let foregroundView: ImageView
private var maskView: ImageView?
private var currentData: Data?
private var currentBackgroundColor: NSColor?
private var currentForegroundColor: NSColor?
private var currentShimmeringColor: NSColor?
private var currentSize = CGSize()
override init() {
self.backgroundView = View()
self.effectView = ShimmerEffectForegroundView()
self.foregroundView = ImageView()
super.init()
self.addSubview(self.backgroundView)
self.addSubview(self.effectView)
self.addSubview(self.foregroundView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
public func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) {
self.effectView.updateAbsoluteRect(rect, within: containerSize)
}
public func update(backgroundColor: NSColor?, foregroundColor: NSColor = NSColor(rgb: 0x748391, alpha: 0.2), shimmeringColor: NSColor = NSColor(rgb: 0x748391, alpha: 0.35), data: Data?, size: CGSize) {
if self.currentData == data, let currentBackgroundColor = self.currentBackgroundColor, currentBackgroundColor.isEqual(backgroundColor), let currentForegroundColor = self.currentForegroundColor, currentForegroundColor.isEqual(foregroundColor), let currentShimmeringColor = self.currentShimmeringColor, currentShimmeringColor.isEqual(shimmeringColor), self.currentSize == size {
return
}
self.currentBackgroundColor = backgroundColor
self.currentForegroundColor = foregroundColor
self.currentShimmeringColor = shimmeringColor
self.currentData = data
self.currentSize = size
self.backgroundView.backgroundColor = foregroundColor
self.effectView.update(backgroundColor: backgroundColor == nil ? .clear : foregroundColor, foregroundColor: shimmeringColor)
let image = generateImage(size, rotatedContext: { size, context in
if let backgroundColor = backgroundColor {
context.setFillColor(backgroundColor.cgColor)
context.setBlendMode(.copy)
context.fill(CGRect(origin: CGPoint(), size: size))
context.setFillColor(NSColor.clear.cgColor)
} else {
context.clear(CGRect(origin: CGPoint(), size: size))
context.setFillColor(NSColor.black.cgColor)
}
if let data = data {
var path = decodeStickerThumbnailData(data)
if !path.hasPrefix("z") {
path = "\(path)z"
}
let reader = PathDataReader(input: path)
let segments = reader.read()
let scale = size.width / 512.0
context.scaleBy(x: scale, y: scale)
renderPath(segments, context: context)
} else {
let path = CGMutablePath()
path.addRoundedRect(in: CGRect(origin: CGPoint(), size: size), cornerWidth: min(min(10, size.height / 2), size.width / 2), cornerHeight: min(min(size.height / 2, 10), size.height / 2))
context.addPath(path)
context.fillPath()
}
})
if backgroundColor == nil {
self.foregroundView.image = nil
let maskView: ImageView
if let current = self.maskView {
maskView = current
} else {
maskView = ImageView()
maskView.frame = CGRect(origin: CGPoint(), size: size)
self.maskView = maskView
self.layer?.mask = maskView.layer
}
} else {
self.foregroundView.image = image
if let _ = self.maskView {
self.layer?.mask = nil
self.maskView = nil
}
}
self.maskView?.image = image
self.backgroundView.frame = CGRect(origin: CGPoint(), size: size)
self.foregroundView.frame = CGRect(origin: CGPoint(), size: size)
self.effectView.frame = CGRect(origin: CGPoint(), size: size)
}
}
open class PathSegment: Equatable {
public enum SegmentType {
case M
case L
case C
case Q
case A
case z
case H
case V
case S
case T
case m
case l
case c
case q
case a
case h
case v
case s
case t
case E
case e
}
public let type: SegmentType
public let data: [Double]
public init(type: PathSegment.SegmentType = .M, data: [Double] = []) {
self.type = type
self.data = data
}
open func isAbsolute() -> Bool {
switch type {
case .M, .L, .H, .V, .C, .S, .Q, .T, .A, .E:
return true
default:
return false
}
}
public static func == (lhs: PathSegment, rhs: PathSegment) -> Bool {
return lhs.type == rhs.type && lhs.data == rhs.data
}
}
private func renderPath(_ segments: [PathSegment], context: CGContext) {
var currentPoint: CGPoint?
var cubicPoint: CGPoint?
var quadrPoint: CGPoint?
var initialPoint: CGPoint?
func M(_ x: Double, y: Double) {
let point = CGPoint(x: CGFloat(x), y: CGFloat(y))
context.move(to: point)
setInitPoint(point)
}
func m(_ x: Double, y: Double) {
if let cur = currentPoint {
let next = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y)
context.move(to: next)
setInitPoint(next)
} else {
M(x, y: y)
}
}
func L(_ x: Double, y: Double) {
lineTo(CGPoint(x: CGFloat(x), y: CGFloat(y)))
}
func l(_ x: Double, y: Double) {
if let cur = currentPoint {
lineTo(CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y))
} else {
L(x, y: y)
}
}
func H(_ x: Double) {
if let cur = currentPoint {
lineTo(CGPoint(x: CGFloat(x), y: CGFloat(cur.y)))
}
}
func h(_ x: Double) {
if let cur = currentPoint {
lineTo(CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(cur.y)))
}
}
func V(_ y: Double) {
if let cur = currentPoint {
lineTo(CGPoint(x: CGFloat(cur.x), y: CGFloat(y)))
}
}
func v(_ y: Double) {
if let cur = currentPoint {
lineTo(CGPoint(x: CGFloat(cur.x), y: CGFloat(y) + cur.y))
}
}
func lineTo(_ p: CGPoint) {
context.addLine(to: p)
setPoint(p)
}
func c(_ x1: Double, y1: Double, x2: Double, y2: Double, x: Double, y: Double) {
if let cur = currentPoint {
let endPoint = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y)
let controlPoint1 = CGPoint(x: CGFloat(x1) + cur.x, y: CGFloat(y1) + cur.y)
let controlPoint2 = CGPoint(x: CGFloat(x2) + cur.x, y: CGFloat(y2) + cur.y)
context.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2)
setCubicPoint(endPoint, cubic: controlPoint2)
}
}
func C(_ x1: Double, y1: Double, x2: Double, y2: Double, x: Double, y: Double) {
let endPoint = CGPoint(x: CGFloat(x), y: CGFloat(y))
let controlPoint1 = CGPoint(x: CGFloat(x1), y: CGFloat(y1))
let controlPoint2 = CGPoint(x: CGFloat(x2), y: CGFloat(y2))
context.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2)
setCubicPoint(endPoint, cubic: controlPoint2)
}
func s(_ x2: Double, y2: Double, x: Double, y: Double) {
if let cur = currentPoint {
let nextCubic = CGPoint(x: CGFloat(x2) + cur.x, y: CGFloat(y2) + cur.y)
let next = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y)
let xy1: CGPoint
if let curCubicVal = cubicPoint {
xy1 = CGPoint(x: CGFloat(2 * cur.x) - curCubicVal.x, y: CGFloat(2 * cur.y) - curCubicVal.y)
} else {
xy1 = cur
}
context.addCurve(to: next, control1: xy1, control2: nextCubic)
setCubicPoint(next, cubic: nextCubic)
}
}
func S(_ x2: Double, y2: Double, x: Double, y: Double) {
if let cur = currentPoint {
let nextCubic = CGPoint(x: CGFloat(x2), y: CGFloat(y2))
let next = CGPoint(x: CGFloat(x), y: CGFloat(y))
let xy1: CGPoint
if let curCubicVal = cubicPoint {
xy1 = CGPoint(x: CGFloat(2 * cur.x) - curCubicVal.x, y: CGFloat(2 * cur.y) - curCubicVal.y)
} else {
xy1 = cur
}
context.addCurve(to: next, control1: xy1, control2: nextCubic)
setCubicPoint(next, cubic: nextCubic)
}
}
func z() {
context.fillPath()
}
func setQuadrPoint(_ p: CGPoint, quadr: CGPoint) {
currentPoint = p
quadrPoint = quadr
cubicPoint = nil
}
func setCubicPoint(_ p: CGPoint, cubic: CGPoint) {
currentPoint = p
cubicPoint = cubic
quadrPoint = nil
}
func setInitPoint(_ p: CGPoint) {
setPoint(p)
initialPoint = p
}
func setPoint(_ p: CGPoint) {
currentPoint = p
cubicPoint = nil
quadrPoint = nil
}
for segment in segments {
var data = segment.data
switch segment.type {
case .M:
M(data[0], y: data[1])
data.removeSubrange(Range(uncheckedBounds: (lower: 0, upper: 2)))
while data.count >= 2 {
L(data[0], y: data[1])
data.removeSubrange((0 ..< 2))
}
case .m:
m(data[0], y: data[1])
data.removeSubrange((0 ..< 2))
while data.count >= 2 {
l(data[0], y: data[1])
data.removeSubrange((0 ..< 2))
}
case .L:
while data.count >= 2 {
L(data[0], y: data[1])
data.removeSubrange((0 ..< 2))
}
case .l:
while data.count >= 2 {
l(data[0], y: data[1])
data.removeSubrange((0 ..< 2))
}
case .H:
H(data[0])
case .h:
h(data[0])
case .V:
V(data[0])
case .v:
v(data[0])
case .C:
while data.count >= 6 {
C(data[0], y1: data[1], x2: data[2], y2: data[3], x: data[4], y: data[5])
data.removeSubrange((0 ..< 6))
}
case .c:
while data.count >= 6 {
c(data[0], y1: data[1], x2: data[2], y2: data[3], x: data[4], y: data[5])
data.removeSubrange((0 ..< 6))
}
case .S:
while data.count >= 4 {
S(data[0], y2: data[1], x: data[2], y: data[3])
data.removeSubrange((0 ..< 4))
}
case .s:
while data.count >= 4 {
s(data[0], y2: data[1], x: data[2], y: data[3])
data.removeSubrange((0 ..< 4))
}
case .z:
z()
default:
print("unknown")
break
}
}
}
private class PathDataReader {
private let input: String
private var current: UnicodeScalar?
private var previous: UnicodeScalar?
private var iterator: String.UnicodeScalarView.Iterator
private static let spaces: Set<UnicodeScalar> = Set("\n\r\t ,".unicodeScalars)
init(input: String) {
self.input = input
self.iterator = input.unicodeScalars.makeIterator()
}
public func read() -> [PathSegment] {
readNext()
var segments = [PathSegment]()
while let array = readSegments() {
segments.append(contentsOf: array)
}
return segments
}
private func readSegments() -> [PathSegment]? {
if let type = readSegmentType() {
let argCount = getArgCount(segment: type)
if argCount == 0 {
return [PathSegment(type: type)]
}
var result = [PathSegment]()
let data: [Double]
if type == .a || type == .A {
data = readDataOfASegment()
} else {
data = readData()
}
var index = 0
var isFirstSegment = true
while index < data.count {
let end = index + argCount
if end > data.count {
break
}
var currentType = type
if type == .M && !isFirstSegment {
currentType = .L
}
if type == .m && !isFirstSegment {
currentType = .l
}
result.append(PathSegment(type: currentType, data: Array(data[index..<end])))
isFirstSegment = false
index = end
}
return result
}
return nil
}
private func readData() -> [Double] {
var data = [Double]()
while true {
skipSpaces()
if let value = readNum() {
data.append(value)
} else {
return data
}
}
}
private func readDataOfASegment() -> [Double] {
let argCount = getArgCount(segment: .A)
var data: [Double] = []
var index = 0
while true {
skipSpaces()
let value: Double?
let indexMod = index % argCount
if indexMod == 3 || indexMod == 4 {
value = readFlag()
} else {
value = readNum()
}
guard let doubleValue = value else {
return data
}
data.append(doubleValue)
index += 1
}
return data
}
private func skipSpaces() {
var currentCharacter = current
while let character = currentCharacter, Self.spaces.contains(character) {
currentCharacter = readNext()
}
}
private func readFlag() -> Double? {
guard let ch = current else {
return .none
}
readNext()
switch ch {
case "0":
return 0
case "1":
return 1
default:
return .none
}
}
fileprivate func readNum() -> Double? {
guard let ch = current else {
return .none
}
guard ch >= "0" && ch <= "9" || ch == "." || ch == "-" else {
return .none
}
var chars = [ch]
var hasDot = ch == "."
while let ch = readDigit(&hasDot) {
chars.append(ch)
}
var buf = ""
buf.unicodeScalars.append(contentsOf: chars)
guard let value = Double(buf) else {
return .none
}
return value
}
fileprivate func readDigit(_ hasDot: inout Bool) -> UnicodeScalar? {
if let ch = readNext() {
if (ch >= "0" && ch <= "9") || ch == "e" || (previous == "e" && ch == "-") {
return ch
} else if ch == "." && !hasDot {
hasDot = true
return ch
}
}
return nil
}
fileprivate func isNum(ch: UnicodeScalar, hasDot: inout Bool) -> Bool {
switch ch {
case "0"..."9":
return true
case ".":
if hasDot {
return false
}
hasDot = true
default:
return true
}
return false
}
@discardableResult
private func readNext() -> UnicodeScalar? {
previous = current
current = iterator.next()
return current
}
private func isAcceptableSeparator(_ ch: UnicodeScalar?) -> Bool {
if let ch = ch {
return "\n\r\t ,".contains(String(ch))
}
return false
}
private func readSegmentType() -> PathSegment.SegmentType? {
while true {
if let type = getPathSegmentType() {
readNext()
return type
}
if readNext() == nil {
return nil
}
}
}
fileprivate func getPathSegmentType() -> PathSegment.SegmentType? {
if let ch = current {
switch ch {
case "M":
return .M
case "m":
return .m
case "L":
return .L
case "l":
return .l
case "C":
return .C
case "c":
return .c
case "Q":
return .Q
case "q":
return .q
case "A":
return .A
case "a":
return .a
case "z", "Z":
return .z
case "H":
return .H
case "h":
return .h
case "V":
return .V
case "v":
return .v
case "S":
return .S
case "s":
return .s
case "T":
return .T
case "t":
return .t
default:
break
}
}
return nil
}
fileprivate func getArgCount(segment: PathSegment.SegmentType) -> Int {
switch segment {
case .H, .h, .V, .v:
return 1
case .M, .m, .L, .l, .T, .t:
return 2
case .S, .s, .Q, .q:
return 4
case .C, .c:
return 6
case .A, .a:
return 7
default:
return 0
}
}
}
| 9f7dd7ce8eed89c30e603fe0821ad4e9 | 29.635938 | 384 | 0.478554 | false | false | false | false |
bizz84/SwiftyStoreKit | refs/heads/master | Sources/SwiftyStoreKit/OS.swift | mit | 1 | //
// OS.swift
// SwiftyStoreKit
//
// Copyright (c) 2020 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import StoreKit
// MARK: - Missing SKMutablePayment init with product on macOS
#if os(OSX)
extension SKMutablePayment {
convenience init(product: SKProduct) {
self.init()
self.productIdentifier = product.productIdentifier
}
}
#endif
// MARK: - Missing SKError on watchOS
#if os(watchOS) && swift(<5.3)
public struct SKError: Error {
public typealias Code = SKErrorCode
let _nsError: NSError
init(_nsError: NSError) {
self._nsError = _nsError
}
public var code: Code {
return Code(rawValue: _nsError.code) ?? .unknown
}
static var unknown: Code = .unknown
static var paymentInvalid: Code = .paymentInvalid
}
#endif
| 7cca4868c9925f154b47e69846eef192 | 33.285714 | 81 | 0.703646 | false | false | false | false |
NextFaze/FazeKit | refs/heads/master | FazeKit/Classes/NSAttributedStringAdditions.swift | apache-2.0 | 2 | //
// NSAttributedStringAdditions.swift
// FazeKit
//
// Created by Shane Woolcock on 10/10/19.
//
import Foundation
public extension NSAttributedString {
func height(withConstrainedWidth width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return ceil(boundingBox.width)
}
// https://medium.com/@rwbutler/trimming-nsattributedstring-b8c1e58ac0a
func trimmingCharacters(in characterSet: CharacterSet) -> NSAttributedString {
guard let result = self.mutableCopy() as? NSMutableAttributedString else { fatalError() }
while let range = result.string.rangeOfCharacter(from: characterSet), range.lowerBound == result.string.startIndex {
let length = result.string.distance(from: range.lowerBound, to: range.upperBound)
result.deleteCharacters(in: NSRange(location: 0, length: length))
}
while let range = result.string.rangeOfCharacter(from: characterSet, options: .backwards), range.upperBound == result.string.endIndex {
let location = result.string.distance(from: result.string.startIndex, to: range.lowerBound)
let length = result.string.distance(from: range.lowerBound, to: range.upperBound)
result.deleteCharacters(in: NSRange(location: location, length: length))
}
return result
}
}
public extension Array where Element: NSAttributedString {
func joined(separator: String = ",") -> NSAttributedString {
return self.joined(attributedSeparator: NSAttributedString(string: separator))
}
func joined(attributedSeparator: NSAttributedString) -> NSAttributedString {
guard !self.isEmpty else { return NSAttributedString() }
let attr = NSMutableAttributedString()
for (offset, element) in self.enumerated() {
if offset > 0 {
attr.append(attributedSeparator)
}
attr.append(element)
}
return attr
}
}
| 14940365dd0f087192a7c1214d678f3f | 42.175439 | 143 | 0.684275 | false | false | false | false |
JohnEstropia/CoreStore | refs/heads/develop | Demo/Sources/Demos/Modern/TimeZonesDemo/Modern.TimeZonesDemo.ListView.swift | mit | 1 | //
// Demo
// Copyright © 2020 John Rommel Estropia, Inc. All rights reserved.
import CoreStore
import SwiftUI
// MARK: - Modern.TimeZonesDemo
extension Modern.TimeZonesDemo {
// MARK: - Modern.TimeZonesDemo.ListView
struct ListView: View {
// MARK: Internal
init(title: String, objects: [Modern.TimeZonesDemo.TimeZone]) {
self.title = title
self.values = objects.map {
(title: $0.name, subtitle: $0.abbreviation)
}
}
init(title: String, value: Any?) {
self.title = title
switch value {
case (let array as [Any])?:
self.values = array.map {
(
title: String(describing: $0),
subtitle: String(reflecting: type(of: $0))
)
}
case let item?:
self.values = [
(
title: String(describing: item),
subtitle: String(reflecting: type(of: item))
)
]
case nil:
self.values = []
}
}
// MARK: View
var body: some View {
List {
ForEach(self.values, id: \.title) { item in
Modern.TimeZonesDemo.ItemView(
title: item.title,
subtitle: item.subtitle
)
}
}
.navigationBarTitle(self.title)
}
// MARK: Private
private let title: String
private let values: [(title: String, subtitle: String)]
}
}
#if DEBUG
struct _Demo_Modern_TimeZonesDemo_ListView_Preview: PreviewProvider {
// MARK: PreviewProvider
static var previews: some View {
Modern.TimeZonesDemo.ListView(
title: "Title",
objects: try! Modern.TimeZonesDemo.dataStack.fetchAll(
From<Modern.TimeZonesDemo.TimeZone>()
.orderBy(.ascending(\.$name))
)
)
}
}
#endif
| e7fefbafc6b39706eea6836acc47b4b8 | 23.691489 | 71 | 0.434726 | false | false | false | false |
brunodlz/Couch | refs/heads/master | Couch/Couch/View/Show/ShowCell.swift | mit | 1 | import UIKit
final class ShowCell: UITableViewCell {
var showView = ShowView(frame: .zero)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let frame = CGRect(x: 0, y: 0, width: bounds.width, height: 100)
showView.frame = frame
contentView.addSubview(showView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(show: Show) {
showView.titleLabel.text = show.title ?? ""
if let year = show.year {
showView.yearLabel.text = "\(year)"
}
ImageManager().download(with: show.imdb, imageView: showView.banner)
}
}
| ccb7b65e863199e5906aeef7b3c7bfd6 | 27.785714 | 76 | 0.602978 | false | false | false | false |
mssun/pass-ios | refs/heads/master | passAutoFillExtension/Services/PasswordsTableDataSource.swift | mit | 2 | //
// PasswordsTableDataSource.swift
// passAutoFillExtension
//
// Created by Sun, Mingshen on 12/31/20.
// Copyright © 2020 Bob Sun. All rights reserved.
//
import passKit
import UIKit
class PasswordsTableDataSource: NSObject, UITableViewDataSource {
var passwordTableEntries: [PasswordTableEntry]
var filteredPasswordsTableEntries: [PasswordTableEntry]
var suggestedPasswordsTableEntries: [PasswordTableEntry]
var otherPasswordsTableEntries: [PasswordTableEntry]
var showSuggestion = false
init(entries: [PasswordTableEntry] = []) {
self.passwordTableEntries = entries
self.filteredPasswordsTableEntries = passwordTableEntries
self.suggestedPasswordsTableEntries = []
self.otherPasswordsTableEntries = []
}
func numberOfSections(in _: UITableView) -> Int {
!showSuggestion ? 1 : 2
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
tableEntries(at: section).count
}
func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
if suggestedPasswordsTableEntries.isEmpty {
return nil
}
if !showSuggestion {
return "All Passwords"
}
if section == 0 {
return "Suggested Passwords"
}
return "Other Passwords"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "passwordTableViewCell", for: indexPath) as! PasswordTableViewCell
let entry = tableEntry(at: indexPath)
cell.configure(with: entry)
return cell
}
func showTableEntries(matching text: String) {
guard !text.isEmpty else {
filteredPasswordsTableEntries = passwordTableEntries
showSuggestion = !suggestedPasswordsTableEntries.isEmpty
return
}
filteredPasswordsTableEntries = passwordTableEntries.filter { $0.matches(text) }
showSuggestion = false
}
func showTableEntriesWithSuggestion(matching text: String) {
guard !text.isEmpty else {
filteredPasswordsTableEntries = passwordTableEntries
showSuggestion = false
return
}
for entry in passwordTableEntries {
if entry.matches(text) {
suggestedPasswordsTableEntries.append(entry)
} else {
otherPasswordsTableEntries.append(entry)
}
}
showSuggestion = !suggestedPasswordsTableEntries.isEmpty
}
func tableEntry(at indexPath: IndexPath) -> PasswordTableEntry {
tableEntries(at: indexPath.section)[indexPath.row]
}
func tableEntries(at section: Int) -> [PasswordTableEntry] {
if showSuggestion {
if section == 0 {
return suggestedPasswordsTableEntries
}
return otherPasswordsTableEntries
}
return filteredPasswordsTableEntries
}
}
| 07da2a004bc5992f0c2aa2c58188c0b2 | 30.255102 | 131 | 0.655893 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/ProfileFeeds/ProfileFeedsCell.swift | mit | 1 | //
// ProfileFeedsCell.swift
// Yep
//
// Created by nixzhu on 15/11/17.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class ProfileFeedsCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var iconImageViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet weak var imageView3: UIImageView!
@IBOutlet weak var imageView4: UIImageView!
@IBOutlet weak var accessoryImageView: UIImageView!
@IBOutlet weak var accessoryImageViewTrailingConstraint: NSLayoutConstraint!
private var enabled: Bool = false {
willSet {
if newValue {
iconImageView.tintColor = UIColor.yepTintColor()
nameLabel.textColor = UIColor.yepTintColor()
accessoryImageView.hidden = false
accessoryImageView.tintColor = UIColor.yepCellAccessoryImageViewTintColor()
} else {
iconImageView.tintColor = SocialAccount.disabledColor
nameLabel.textColor = SocialAccount.disabledColor
accessoryImageView.hidden = true
}
}
}
var feedAttachments: [DiscoveredAttachment?]? {
willSet {
guard let _attachments = newValue else {
return
}
enabled = !_attachments.isEmpty
// 对于从左到右排列,且左边的最新,要处理数量不足的情况
var attachments = _attachments
let imageViews = [
imageView4,
imageView3,
imageView2,
imageView1,
]
let shortagesCount = max(imageViews.count - attachments.count, 0)
// 不足补空
if shortagesCount > 0 {
let shortages = Array<DiscoveredAttachment?>(count: shortagesCount, repeatedValue: nil)
attachments.insertContentsOf(shortages, at: 0)
}
for i in 0..<imageViews.count {
if i < shortagesCount {
imageViews[i].image = nil
} else {
if let thumbnailImage = attachments[i]?.thumbnailImage {
imageViews[i].image = thumbnailImage
} else {
imageViews[i].image = UIImage.yep_iconFeedText
}
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
enabled = false
nameLabel.text = NSLocalizedString("Feeds", comment: "")
iconImageViewLeadingConstraint.constant = YepConfig.Profile.leftEdgeInset
accessoryImageViewTrailingConstraint.constant = YepConfig.Profile.rightEdgeInset
imageView1.contentMode = .ScaleAspectFill
imageView2.contentMode = .ScaleAspectFill
imageView3.contentMode = .ScaleAspectFill
imageView4.contentMode = .ScaleAspectFill
let cornerRadius: CGFloat = 2
imageView1.layer.cornerRadius = cornerRadius
imageView2.layer.cornerRadius = cornerRadius
imageView3.layer.cornerRadius = cornerRadius
imageView4.layer.cornerRadius = cornerRadius
imageView1.clipsToBounds = true
imageView2.clipsToBounds = true
imageView3.clipsToBounds = true
imageView4.clipsToBounds = true
}
func configureWithProfileUser(profileUser: ProfileUser?, feedAttachments: [DiscoveredAttachment?]?, completion: ((feeds: [DiscoveredFeed], feedAttachments: [DiscoveredAttachment?]) -> Void)?) {
if let feedAttachments = feedAttachments {
self.feedAttachments = feedAttachments
} else {
guard let profileUser = profileUser else {
return
}
feedsOfUser(profileUser.userID, pageIndex: 1, perPage: 20, failureHandler: nil, completion: { validFeeds, _ in
println("user's feeds: \(validFeeds.count)")
let feedAttachments = validFeeds.map({ feed -> DiscoveredAttachment? in
if let attachment = feed.attachment {
if case let .Images(attachments) = attachment {
return attachments.first
}
}
return nil
})
SafeDispatch.async { [weak self] in
self?.feedAttachments = feedAttachments
completion?(feeds: validFeeds, feedAttachments: feedAttachments)
}
})
}
}
}
| fd8aa3c3cb2e8e2c7c1ca482e9e0721e | 32.126761 | 197 | 0.590774 | false | false | false | false |
AngeloStavrow/Rewatch | refs/heads/master | Rewatch/Domain/DownloadController.swift | mit | 1 | //
// DownloadController.swift
// Rewatch
//
// Created by Romain Pouclet on 2015-11-04.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import UIKit
import ReactiveCocoa
import Result
import CoreData
let DownloadControllerLastSyncKey = "LastSyncKey"
func lastSyncDate() -> String? {
guard let date = NSUserDefaults.standardUserDefaults().objectForKey(DownloadControllerLastSyncKey) as? NSDate else {
return nil
}
let formatter = NSDateFormatter()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
return formatter.stringFromDate(date)
}
class DownloadController: NSObject {
let client: Client
let persistenceController: PersistenceController
init(client: Client, persistenceController: PersistenceController) {
self.client = client
self.persistenceController = persistenceController
super.init()
}
/// Download the content needed to run the application
/// and returns the number of episodes available for the random
func download() -> SignalProducer<Int, NSError> {
let importMoc = persistenceController.spawnManagedObjectContext()
let importScheduler = PersistenceScheduler(context: importMoc)
return client
.fetchShows()
.flatMap(FlattenStrategy.Merge, transform: { (show) -> SignalProducer<StoredShow, NSError> in
return SignalProducer { observable, disposable in
observable.sendNext(StoredShow.showInContext(importMoc, mappedOnShow: show))
observable.sendCompleted()
}.startOn(importScheduler)
})
.flatMap(.Merge, transform: { (storedShow) -> SignalProducer<(StoredShow, StoredEpisode), NSError> in
let fetchEpisodeSignal = self.fetchSeenEpisodeFromShow(Int(storedShow.id))
.flatMap(FlattenStrategy.Merge, transform: { (episode) -> SignalProducer<StoredEpisode, NSError> in
return SignalProducer { observable, disposable in
let storedEpisode = StoredEpisode.episodeInContext(importMoc, mappedOnEpisode: episode)
storedEpisode.show = storedShow
observable.sendNext(storedEpisode)
observable.sendCompleted()
}.startOn(importScheduler)
})
return combineLatest(SignalProducer(value: storedShow), fetchEpisodeSignal)
})
.collect()
.flatMap(.Latest, transform: { (shows) -> SignalProducer<Int, NSError> in
return SignalProducer { sink, disposable in
try! importMoc.save()
sink.sendNext(shows.count)
sink.sendCompleted()
}
})
.on(next: { print("Synchronized \($0) episodes") }, completed: {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(NSDate(), forKey: DownloadControllerLastSyncKey)
defaults.synchronize()
})
}
func fetchSeenEpisodeFromShow(id: Int) -> SignalProducer<Client.Episode, NSError> {
return self.client
.fetchEpisodesFromShow(id)
.filter({ $0.seen })
}
}
| 6916a7e9de58b65d5ea133495f0abacd | 38.488372 | 121 | 0.61808 | false | false | false | false |
coderMONSTER/ioscelebrity | refs/heads/master | YStar/YStar/General/Base/AlertViewController.swift | mit | 1 | //
// AlertViewController.swift
// iOSStar
//
// Created by MONSTER on 2017/5/27.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
// 屏幕宽高
private var kSCREEN_W : CGFloat = UIScreen.main.bounds.size.width
private var kSCREEN_H : CGFloat = UIScreen.main.bounds.size.height
class AlertViewController: UIViewController {
// 对这个强引用
var strongSelf:AlertViewController?
// 按钮动作
var completeAction:((_ button: UIButton) -> Void)? = nil
// 内部控件
var contentView = UIView()
var closeButton = UIButton()
var picImageView = UIImageView()
var titleLabel = UILabel()
var subTitleTextView = UITextView();
var completeButton = UIButton()
init() {
super.init(nibName: nil, bundle: nil)
self.view.frame = UIScreen.main.bounds
self.view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0.7)
self.view.addSubview(contentView)
//强引用 不然按钮点击不能执行
strongSelf = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("AlertViewController --- deinit ");
}
// MARK : - 初始化UI
fileprivate func setupContentView() {
contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0);
contentView.layer.cornerRadius = 3.0
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
view.addSubview(contentView);
contentView.addSubview(closeButton)
contentView.addSubview(picImageView)
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleTextView)
contentView.addSubview(completeButton)
}
//关闭按钮
fileprivate func setupCloseButton() {
let closeButtonIconFont = UIImage.imageWith(AppConst.iconFontName.closeIcon.rawValue, fontSize: CGSize.init(width: 16, height: 16), fontColor: UIColor.init(rgbHex: 0x999999))
closeButton.setImage(closeButtonIconFont, for: .normal)
self.closeButton.addTarget(self, action: #selector(closeButtonClick(_ :)), for: .touchUpInside);
}
// 图片
fileprivate func setupPicImageView() {
picImageView.contentMode = .scaleAspectFit
}
// 标题
fileprivate func setupTitleLabel() {
titleLabel.text = ""
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.colorFromRGB(0x333333)
titleLabel.font = UIFont.systemFont(ofSize: 16.0)
}
// 文本
fileprivate func setupSubTitleTextView() {
subTitleTextView.text = ""
// subTitleTextView.textAlignment = .center
subTitleTextView.font = UIFont.systemFont(ofSize: 14.0)
// subTitleTextView.textColor = UIColor.colorFromRGB(0x999999)
subTitleTextView.isEditable = false
subTitleTextView.isScrollEnabled = false
subTitleTextView.isSelectable = false
}
// 按钮
fileprivate func setupCompleteButton(){
completeButton.backgroundColor = UIColor.colorFromRGB(0x8C0808)
completeButton.titleLabel?.textColor = UIColor.colorFromRGB(0xFAFAFA)
completeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
completeButton.addTarget(self, action: #selector(completeButtonButtonClick(_ :)), for: .touchUpInside)
}
}
// MARK: -布局
extension AlertViewController {
fileprivate func resizeAndLayout() {
let mainScreenBounds = UIScreen.main.bounds
self.view.frame.size = mainScreenBounds.size
var kLEFT_MARGIN :CGFloat = 0
var kTOP_MARGIN :CGFloat = 0
if kSCREEN_H == 568 {
kLEFT_MARGIN = 19
kTOP_MARGIN = 59
} else {
kLEFT_MARGIN = 37
kTOP_MARGIN = 118
}
// let kLEFT_MARGIN :CGFloat = kSCREEN_W * 0.1
// let kTOP_MARGIN : CGFloat = kSCREEN_H * 0.085
contentView.frame = CGRect(x: kLEFT_MARGIN,
y: kTOP_MARGIN,
width: kSCREEN_W - (kLEFT_MARGIN * 2) ,
height: kSCREEN_H - (kTOP_MARGIN * 2))
closeButton.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(16)
make.right.equalToSuperview().offset(-16)
make.width.height.equalTo(16)
}
// picImageView.frame = CGRect(x: 69, y: 52, width: 164, height: 164)
picImageView.snp.makeConstraints { (make) in
make.top.equalTo(contentView.snp.top).offset(50)
make.centerX.equalToSuperview()
make.width.equalToSuperview()
make.height.equalTo(160)
}
titleLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(picImageView.snp.bottom).offset(20)
}
subTitleTextView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.left.equalToSuperview().offset(16)
make.right.equalToSuperview().offset(-16)
make.top.equalTo(titleLabel.snp.bottom).offset(25)
}
completeButton.snp.makeConstraints { (make) in
make.left.bottom.right.equalTo(contentView).offset(0)
make.height.equalTo(51)
}
contentView.transform = CGAffineTransform(translationX: 0, y: -kSCREEN_H / 2)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
self.contentView.transform = CGAffineTransform.identity
}, completion: nil)
}
}
// MARK: - show
extension AlertViewController {
// show
func showAlertVc(imageName : String , titleLabelText : String , subTitleText : String , completeButtonTitle : String , action:@escaping ((_ completeButton: UIButton) -> Void)) {
let window: UIWindow = UIApplication.shared.keyWindow!
window.addSubview(view)
window.bringSubview(toFront: view)
view.frame = window.bounds
completeAction = action;
setupContentView()
setupCloseButton()
setupPicImageView()
setupTitleLabel()
setupSubTitleTextView()
setupCompleteButton()
self.picImageView.image = UIImage(named: "\(imageName)")
self.titleLabel.text = titleLabelText
// 设置行间距?
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
paragraphStyle.alignment = .center
let attributes = [NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName:UIColor.colorFromRGB(0x999999)]
self.subTitleTextView.attributedText = NSAttributedString(string: subTitleText, attributes: attributes)
// self.subTitleTextView.text = subTitleText;
self.completeButton.setTitle("\(completeButtonTitle)", for: .normal);
resizeAndLayout()
}
// dismiss
func dismissAlertVc() {
UIView.animate(withDuration: 0, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.view.alpha = 0.0
self.contentView.transform = CGAffineTransform(translationX: 0, y: kSCREEN_H)
}) { (Bool) -> Void in
self.view.removeFromSuperview()
self.contentView.removeFromSuperview()
self.contentView = UIView()
self.strongSelf = nil
}
}
}
// MARK: - AlertViewController 点击事件
extension AlertViewController {
func closeButtonClick(_ sender: UIButton) {
dismissAlertVc()
}
func completeButtonButtonClick(_ sender : UIButton) {
if completeAction != nil {
completeAction!(sender)
}
}
}
// MARK: - 点击任意位置退出dismiss
extension AlertViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dismissAlertVc()
}
}
extension UIColor {
class func colorFromRGB(_ rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
| b78c0040543c0dda4f2c6696ee874ff1 | 31.188406 | 182 | 0.606258 | false | false | false | false |
rbaladron/SwiftProgramaParaiOS | refs/heads/master | Ejercicios/TestSemana3.playground/Contents.swift | mit | 1 | //: Funciones, opcioales, tuplas y enumeraciones
import UIKit
// 1 . ¿Cuál función imprime saludos más tu nombre?
func saludos( nombre : String ){
print(" saludos \(nombre)!!!!")
}
saludos("Roberto")
// 2. Selecciona la función que convierte tu edad en años en los meses que has vivido. Tanto el valor de retorno y el parámetro que recibe la función deben ser de tipo entero.
func convierteAñosEnMeses( años : Int ) -> Int{
return años * 12
}
convierteAñosEnMeses(20)
// 3. ¿Qué imprime el siguiente código?
let variableOpcional : Int? = 90
if variableOpcional != nil {
print("El valor es: \(variableOpcional!)")
}else{
print("El valor es: nil")
}
//4 .En base a la siguiente función:
func misteriosa (variableA : Int, variableB : Int) -> Int {
if variableA >= variableB {
return variableA
}else {
return variableB
}
}
misteriosa(50, variableB: 90)
misteriosa(50, variableB: 50)
misteriosa(90, variableB: 91)
misteriosa(50, variableB: 100)
misteriosa(-1, variableB: -2)
//5 .Selecciona la función obtenClienteVip que regrese una tupla con la edad (Int), nombre (String) y presupuesto (Double) con sus respectivos nombres de atributos, debe coincidir con el valor declarado en return.
func obtenClienteVip()-> ( edad : Int,nombre : String, presupuesto:Double ){
return (40, "Alejandro", 1545.70)
}
obtenClienteVip()
//6. En base a la siguiente declaración de una tupla:
let tupla = (nombre : "Marco", peso: 70.6, altura: 1.90)
//Selecciona todas las opciones correctas para obtener los atributos de nombre y altura.
tupla.0
tupla.2
tupla.nombre
tupla.altura
// 7. Selecciona todas las sentencias que declaren e asignen un valor inicial a un opcional.
let letra : Bool? = nil
let cantidad : Double? = nil
let espacio : String? = "____"
//8. Selecciona las enumeraciones declaradas correctamente.
enum TiposDeCafe : String{
case Ligero = "Sin cafeína", Medio = "Del Mediterraneo", Fuerte = "Extra Expresso"
}
TiposDeCafe.Fuerte
enum Codigos{
case Secreto(Int, String, Double)
}
Codigos.Secreto(5, "Tierra", 123.0)
enum Canciones{
case Infinito, BajoElSol, UnBeso
}
Canciones.BajoElSol
// 9. Toma como base el siguiente código:
enum Planetas : Int {
case Tierra = 305, Marte = 400, Jupiter = 500
init () {
self = .Marte
}
func calculaDistancia ( dato: Planetas) -> Int {
return self.rawValue - dato.rawValue
}
}
let planeta = Planetas()
planeta.calculaDistancia(Planetas.Jupiter)
planeta.calculaDistancia(Planetas.Tierra)
//10.El atributo de rawValue, dentro de una enumeración, sirve para inicializar la enumeración.
//Verdadero
| 00cd267e2813d903dd335392021946f6 | 19.984733 | 213 | 0.681702 | false | false | false | false |
soapyigu/LeetCode_Swift | refs/heads/master | Array/TaskScheduler.swift | mit | 1 | /**
* Question Link: https://leetcode.com/problems/task-scheduler/
* Primary idea: Most frequent character should be put at head of each chunk and join the chunks with less frequent one.
*
* Time Complexity: O(nlogn), Space Complexity: O(n)
*
*/
class TaskScheduler {
func leastInterval(_ tasks: [Character], _ n: Int) -> Int {
guard tasks.count > 0 else {
return 0
}
let taskFreqs = Dictionary(tasks.map { ($0, 1) }, uniquingKeysWith: +)
let sortedTasks = taskFreqs.keys.sorted { return taskFreqs[$0]! > taskFreqs[$1]! }
var mostFreqCount = 0
for sortedTask in sortedTasks {
if taskFreqs[sortedTask] != taskFreqs[sortedTasks[0]] {
break
}
mostFreqCount += 1
}
return max(tasks.count, (taskFreqs[sortedTasks[0]]! - 1) * (n + 1) + mostFreqCount)
}
} | 21b1b93661e43f8c3fb7104dbf8a642d | 31.241379 | 120 | 0.568522 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/Lightsail/Lightsail_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Lightsail
public struct LightsailErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case accountSetupInProgressException = "AccountSetupInProgressException"
case invalidInputException = "InvalidInputException"
case notFoundException = "NotFoundException"
case operationFailureException = "OperationFailureException"
case serviceException = "ServiceException"
case unauthenticatedException = "UnauthenticatedException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Lightsail
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Lightsail throws this exception when the user cannot be authenticated or uses invalid credentials to access a resource.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// Lightsail throws this exception when an account is still in the setup in progress state.
public static var accountSetupInProgressException: Self { .init(.accountSetupInProgressException) }
/// Lightsail throws this exception when user input does not conform to the validation rules of an input field. Domain-related APIs are only available in the N. Virginia (us-east-1) Region. Please set your AWS Region configuration to us-east-1 to create, view, or edit these resources.
public static var invalidInputException: Self { .init(.invalidInputException) }
/// Lightsail throws this exception when it cannot find a resource.
public static var notFoundException: Self { .init(.notFoundException) }
/// Lightsail throws this exception when an operation fails to execute.
public static var operationFailureException: Self { .init(.operationFailureException) }
/// A general service exception.
public static var serviceException: Self { .init(.serviceException) }
/// Lightsail throws this exception when the user has not been authenticated.
public static var unauthenticatedException: Self { .init(.unauthenticatedException) }
}
extension LightsailErrorType: Equatable {
public static func == (lhs: LightsailErrorType, rhs: LightsailErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension LightsailErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 263916a67238955bb92fc54499e0367b | 44.026667 | 290 | 0.695588 | false | false | false | false |
thachpv91/loafwallet | refs/heads/master | BreadWallet/BRWebSocket.swift | mit | 1 | //
// BRWebSocket.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/18/16.
// Copyright (c) 2016 breadwallet LLC
// Copyright © 2016 Litecoin Association <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@objc public protocol BRWebSocket {
var id: String { get }
var request: BRHTTPRequest { get }
var match: BRHTTPRouteMatch { get }
func send(_ text: String)
}
@objc public protocol BRWebSocketClient {
@objc optional func socketDidConnect(_ socket: BRWebSocket)
@objc optional func socket(_ socket: BRWebSocket, didReceiveData data: Data)
@objc optional func socket(_ socket: BRWebSocket, didReceiveText text: String)
@objc optional func socketDidDisconnect(_ socket: BRWebSocket)
}
let GID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
enum SocketState {
case headerb1
case headerb2
case lengthshort
case lengthlong
case mask
case payload
}
enum SocketOpcode: UInt8, CustomStringConvertible {
case stream = 0x0
case text = 0x1
case binary = 0x2
case close = 0x8
case ping = 0x9
case pong = 0xA
var description: String {
switch (self) {
case .stream: return "STREAM"
case .text: return "TEXT"
case .binary: return "BINARY"
case .close: return "CLOSE"
case .ping: return "PING"
case .pong: return "PONG"
}
}
}
let (MAXHEADER, MAXPAYLOAD) = (65536, 33554432)
enum SocketCloseEventCode: UInt16 {
case close_NORMAL = 1000
case close_GOING_AWAY = 1001
case close_PROTOCOL_ERROR = 1002
case close_UNSUPPORTED = 1003
case close_NO_STATUS = 1005
case close_ABNORMAL = 1004
case unsupportedData = 1006
case policyViolation = 1007
case close_TOO_LARGE = 1008
case missingExtension = 1009
case internalError = 1010
case serviceRestart = 1011
case tryAgainLater = 1012
case tlsHandshake = 1015
}
class BRWebSocketServer {
var sockets = [Int32: BRWebSocketImpl]()
var thread: pthread_t? = nil
var waiter: UnsafeMutablePointer<pthread_cond_t>
var mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
mutex = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_mutex_t>.size)
waiter = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_cond_t>.size)
pthread_mutex_init(mutex, nil)
pthread_cond_init(waiter, nil)
}
func add(_ socket: BRWebSocketImpl) {
log("adding socket \(socket.fd)")
pthread_mutex_lock(mutex)
sockets[socket.fd] = socket
socket.client.socketDidConnect?(socket)
pthread_cond_broadcast(waiter)
pthread_mutex_unlock(mutex)
log("done adding socket \(socket.fd)")
}
func serveForever() {
objc_sync_enter(self)
if thread != nil {
objc_sync_exit(self)
return
}
let selfPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
pthread_create(&thread, nil, { (sillySelf: UnsafeMutableRawPointer) in
let localSelf = Unmanaged<BRWebSocketServer>.fromOpaque(sillySelf).takeUnretainedValue()
localSelf.log("in server thread")
localSelf._serveForever()
return nil
}, selfPointer)
objc_sync_exit(self)
}
func _serveForever() {
log("starting websocket poller")
while true {
pthread_mutex_lock(mutex)
while sockets.count < 1 {
log("awaiting clients")
pthread_cond_wait(waiter, mutex)
}
pthread_mutex_unlock(mutex)
// log("awaiting select")
// all fds should be available for a read
let readFds = sockets.map({ (ws) -> Int32 in return ws.0 });
// only fds which have items in the send queue are available for a write
let writeFds = sockets.map({
(ws) -> Int32 in return ws.1.sendq.count > 0 ? ws.0 : -1
}).filter({ i in return i != -1 })
// build the select request and execute it, checking the result for an error
let req = bw_select_request(
write_fd_len: Int32(writeFds.count),
read_fd_len: Int32(readFds.count),
write_fds: UnsafeMutablePointer(mutating: writeFds),
read_fds: UnsafeMutablePointer(mutating: readFds));
let resp = bw_select(req)
if resp.error > 0 {
let errstr = strerror(resp.error)
log("error doing a select \(errstr) - removing all clients")
sockets.removeAll()
continue
}
// read for all readers that have data waiting
for i in 0..<resp.read_fd_len {
log("handle read fd \(sockets[resp.read_fds[Int(i)]]!.fd)")
if let readSock = sockets[resp.read_fds[Int(i)]] {
readSock.handleRead()
}
}
// write for all writers
for i in 0..<resp.write_fd_len {
log("handle write fd=\(sockets[resp.write_fds[Int(i)]]!.fd)")
if let writeSock = sockets[resp.write_fds[Int(i)]] {
let (opcode, payload) = writeSock.sendq.removeFirst()
do {
let sentBytes = try sendBuffer(writeSock.fd, buffer: payload)
if sentBytes != payload.count {
let remaining = Array(payload.suffix(from: sentBytes - 1))
writeSock.sendq.insert((opcode, remaining), at: 0)
break // terminate sends and continue sending on the next select
} else {
if opcode == .close {
log("KILLING fd=\(writeSock.fd)")
writeSock.response.kill()
writeSock.client.socketDidDisconnect?(writeSock)
sockets.removeValue(forKey: writeSock.fd)
continue // go to the next select client
}
}
} catch {
// close...
writeSock.response.kill()
writeSock.client.socketDidDisconnect?(writeSock)
sockets.removeValue(forKey: writeSock.fd)
}
}
}
// kill sockets that wrote out of bound data
for i in 0..<resp.error_fd_len {
if let errSock = sockets[resp.error_fds[Int(i)]] {
errSock.response.kill()
errSock.client.socketDidDisconnect?(errSock)
sockets.removeValue(forKey: errSock.fd)
}
}
}
}
// attempt to send a buffer, returning the number of sent bytes
func sendBuffer(_ fd: Int32, buffer: [UInt8]) throws -> Int {
log("send buffer fd=\(fd) buffer=\(buffer)")
var sent = 0
try buffer.withUnsafeBufferPointer { pointer in
while sent < buffer.count {
let s = send(fd, pointer.baseAddress! + sent, Int(buffer.count - sent), 0)
log("write result \(s)")
if s <= 0 {
let serr = Int32(s)
// full buffer, should try again next iteration
if Int32(serr) == EWOULDBLOCK || Int32(serr) == EAGAIN {
return
} else {
self.log("socket write failed fd=\(fd) err=\(strerror(serr))")
throw BRHTTPServerError.socketWriteFailed
}
}
sent += s
}
}
return sent
}
func log(_ s: String) {
print("[BRWebSocketHost] \(s)")
}
}
class BRWebSocketImpl: BRWebSocket {
@objc var request: BRHTTPRequest
var response: BRHTTPResponse
@objc var match: BRHTTPRouteMatch
var client: BRWebSocketClient
var fd: Int32
var key: String!
var version: String!
@objc var id: String = UUID().uuidString
var state = SocketState.headerb1
var fin: UInt8 = 0
var hasMask = false
var opcode = SocketOpcode.stream
var closed = false
var index = 0
var length = 0
var lengtharray = [UInt8]()
var lengtharrayWritten = 0
var data = [UInt8]()
var dataWritten = 0
var maskarray = [UInt8]()
var maskarrayWritten = 0
var fragStart = false
var fragType = SocketOpcode.binary
var fragBuffer = [UInt8]()
var sendq = [(SocketOpcode, [UInt8])]()
init(request: BRHTTPRequest, response: BRHTTPResponse, match: BRHTTPRouteMatch, client: BRWebSocketClient) {
self.request = request
self.match = match
self.fd = request.fd
self.response = response
self.client = client
}
// MARK: - public interface impl
@objc func send(_ text: String) {
sendMessage(false, opcode: .text, data: [UInt8](text.utf8))
}
// MARK: - private interface
func handshake() -> Bool {
log("handshake initiated")
if let upgrades = request.headers["upgrade"] , upgrades.count > 0 {
let upgrade = upgrades[0]
if upgrade.lowercased() == "websocket" {
if let ks = request.headers["sec-websocket-key"], let vs = request.headers["sec-websocket-version"]
, ks.count > 0 && vs.count > 0 {
key = ks[0]
version = vs[0]
do {
let acceptStr = "\(key)\(GID)" as NSString
// let acceptData = Data(bytes: UnsafePointer<UInt8>(acceptStr.utf8String!),
// let acceptData = Data(bytes: acceptStr)
// count: acceptStr.lengthOfBytes(using: String.Encoding.utf8.rawValue));
if var acceptStrBytes = acceptStr.utf8String {
let acceptData = NSData(
bytes: &acceptStrBytes,
length: acceptStr.lengthOfBytes(using: String.Encoding.utf8.rawValue))
let acceptEncodedStr = NSData(uInt160: (acceptData as NSData).sha1()).base64EncodedString(options: [])
try response.writeUTF8("HTTP/1.1 101 Switching Protocols\r\n")
try response.writeUTF8("Upgrade: WebSocket\r\n")
try response.writeUTF8("Connection: Upgrade\r\n")
try response.writeUTF8("Sec-WebSocket-Accept: \(acceptEncodedStr)\r\n\r\n")
}
} catch let e {
log("error writing handshake: \(e)")
return false
}
log("handshake written to socket")
// enter non-blocking mode
if !setNonBlocking() {
return false
}
return true
}
log("invalid handshake - missing sec-websocket-key or sec-websocket-version")
}
}
log("invalid handshake - missing or malformed \"upgrade\" header")
return false
}
func setNonBlocking() -> Bool {
log("setting socket to non blocking")
let nbResult = bw_nbioify(request.fd)
if nbResult < 0 {
log("unable to set socket to non blocking \(nbResult)")
return false
}
return true
}
func handleRead() {
var buf = [UInt8](repeating: 0, count: 1)
let n = recv(fd, &buf, 1, 0)
if n <= 0 {
return // failed read - figure out what to do here i guess
}
parseMessage(buf[0])
}
func parseMessage(_ byte: UInt8) {
if state == .headerb1 {
fin = byte & UInt8(0x80)
guard let opc = SocketOpcode(rawValue: byte & UInt8(0x0F)) else {
log("invalid opcode")
return
}
opcode = opc
log("parse HEADERB1 fin=\(fin) opcode=\(opcode)")
state = .headerb2
index = 0
length = 0
let rsv = byte & 0x70
if rsv != 0 {
// fail out here probably
log("rsv bit is not zero! wat!")
return
}
} else if state == .headerb2 {
let mask = byte & 0x80
let length = byte & 0x7F
if opcode == .ping {
log("ping packet is too large! wat!")
return
}
hasMask = mask == 128
if length <= 125 {
self.length = Int(length)
if hasMask {
maskarray = [UInt8](repeating: 0, count: 4)
maskarrayWritten = 0
state = .mask
} else {
// there is no mask and no payload then we're done
if length <= 0 {
handlePacket()
data = [UInt8]()
dataWritten = 0
state = .headerb1
} else {
// there is no mask and some payload
data = [UInt8](repeating: 0, count: self.length)
dataWritten = 0
state = .payload
}
}
} else if length == 126 {
lengtharray = [UInt8](repeating: 0, count: 2)
lengtharrayWritten = 0
state = .lengthshort
} else if length == 127 {
lengtharray = [UInt8](repeating: 0, count: 8)
lengtharrayWritten = 0
state = .lengthlong
}
log("parse HEADERB2 hasMask=\(hasMask) opcode=\(opcode)")
} else if state == .lengthshort {
lengtharrayWritten += 1
if lengtharrayWritten > 2 {
log("short length exceeded allowable size! wat!")
return
}
lengtharray[lengtharrayWritten - 1] = byte
if lengtharrayWritten == 2 {
let ll = Data(bytes: lengtharray).withUnsafeBytes({ (p: UnsafePointer<UInt16>) -> UInt16 in
if Int(OSHostByteOrder()) != OSBigEndian {
return CFSwapInt16BigToHost(p.pointee)
}
return p.pointee
})
length = Int(ll)
if hasMask {
maskarray = [UInt8](repeating: 0, count: 4)
maskarrayWritten = 0
state = .mask
} else {
if length <= 0 {
handlePacket()
data = [UInt8]()
dataWritten = 0
state = .headerb1
} else {
data = [UInt8](repeating: 0, count: length)
dataWritten = 0
state = .payload
}
}
}
log("parse LENGTHSHORT lengtharrayWritten=\(lengtharrayWritten) length=\(length) state=\(state) opcode=\(opcode)")
} else if state == .lengthlong {
lengtharrayWritten += 1
if lengtharrayWritten > 8 {
log("long length exceeded allowable size! wat!")
return
}
lengtharray[lengtharrayWritten - 1] = byte
if lengtharrayWritten == 8 {
let ll = Data(bytes: lengtharray).withUnsafeBytes({ (p: UnsafePointer<UInt64>) -> UInt64 in
if Int(OSHostByteOrder()) != OSBigEndian {
return CFSwapInt64BigToHost(p.pointee)
}
return p.pointee
})
length = Int(ll)
if hasMask {
maskarray = [UInt8](repeating: 0, count: 4)
maskarrayWritten = 0
state = .mask
} else {
if length <= 0 {
handlePacket()
data = [UInt8]()
dataWritten = 0
state = .headerb1
} else {
data = [UInt8](repeating: 0, count: length)
dataWritten = 0
state = .payload
}
}
}
log("parse LENGTHLONG lengtharrayWritten=\(lengtharrayWritten) length=\(length) state=\(state) opcode=\(opcode)")
} else if state == .mask {
maskarrayWritten += 1
if lengtharrayWritten > 4 {
log("mask exceeded allowable size! wat!")
return
}
maskarray[maskarrayWritten - 1] = byte
if maskarrayWritten == 4 {
if length <= 0 {
handlePacket()
data = [UInt8]()
dataWritten = 0
state = .headerb1
} else {
data = [UInt8](repeating: 0, count: length)
dataWritten = 0
state = .payload
}
}
log("parse MASK maskarrayWritten=\(maskarrayWritten) state=\(state)")
} else if state == .payload {
dataWritten += 1
if dataWritten >= MAXPAYLOAD {
log("payload exceed allowable size! wat!")
return
}
if hasMask {
log("payload byte length=\(length) mask=\(maskarray[index%4]) byte=\(byte)")
data[dataWritten - 1] = byte ^ maskarray[index % 4]
} else {
log("payload byte length=\(length) \(byte)")
data[dataWritten - 1] = byte
}
if index + 1 == length {
log("payload done")
handlePacket()
data = [UInt8]()
dataWritten = 0
state = .headerb1
} else {
index += 1
}
}
}
func handlePacket() {
log("handle packet state=\(state) opcode=\(opcode)")
// validate opcode
if opcode == .close || opcode == .stream || opcode == .text || opcode == .binary {
// valid
} else if opcode == .pong || opcode == .ping {
if dataWritten > 125 {
log("control frame length can not be > 125")
return
}
} else {
log("unknown opcode")
return
}
if opcode == .close {
log("CLOSE")
var status = SocketCloseEventCode.close_NORMAL
var reason = ""
if dataWritten >= 2 {
let lt = Array(data.prefix(2))
let ll = Data(bytes: lt).withUnsafeBytes({ (p: UnsafePointer<UInt16>) -> UInt16 in
return CFSwapInt16BigToHost(p.pointee)
})
if let ss = SocketCloseEventCode(rawValue: ll) {
status = ss
} else {
status = .close_PROTOCOL_ERROR
}
let lr = Array(data.suffix(from: 2))
if lr.count > 0 {
if let rr = String(bytes: lr, encoding: String.Encoding.utf8) {
reason = rr
} else {
log("bad utf8 data in close reason string...")
status = .close_PROTOCOL_ERROR
reason = "bad UTF8 data"
}
}
} else {
status = .close_PROTOCOL_ERROR
}
close(status, reason: reason)
} else if fin == 0 {
log("getting fragment \(fin)")
if opcode != .stream {
if opcode == .ping || opcode == .pong {
log("error: control messages can not be fragmented")
return
}
// start of fragments
fragType = opcode
fragStart = true
fragBuffer = fragBuffer + data
} else {
if !fragStart {
log("error: fragmentation protocol error y")
return
}
fragBuffer = fragBuffer + data
}
} else {
if opcode == .stream {
if !fragStart {
log("error: fragmentation protocol error x")
return
}
if self.fragType == .text {
if let str = String(bytes: data, encoding: String.Encoding.utf8) {
self.client.socket?(self, didReceiveText: str)
} else {
log("error decoding utf8 data")
}
} else {
let bin = Data(bytes: UnsafePointer<UInt8>(UnsafePointer(data)), count: data.count)
self.client.socket?(self, didReceiveData: bin)
}
fragType = .binary
fragStart = false
fragBuffer = [UInt8]()
} else if opcode == .ping {
sendMessage(false, opcode: .pong, data: data)
} else if opcode == .pong {
// nothing to do
} else {
if fragStart {
log("error: fragment protocol error z")
return
}
if opcode == .text {
if let str = String(bytes: data, encoding: String.Encoding.utf8) {
self.client.socket?(self, didReceiveText: str)
} else {
log("error decoding uft8 data")
}
}
}
}
}
func close(_ status: SocketCloseEventCode = .close_NORMAL, reason: String = "") {
if !closed {
log("sending close")
sendMessage(false, opcode: .close, data: status.rawValue.toNetwork() + [UInt8](reason.utf8))
} else {
log("socket is already closed")
}
closed = true
}
func sendMessage(_ fin: Bool, opcode: SocketOpcode, data: [UInt8]) {
log("send message opcode=\(opcode)")
var b1: UInt8 = 0
var b2: UInt8 = 0
if !fin { b1 |= 0x80 }
var payload = [UInt8]() // todo: pick the right size for this
b1 |= opcode.rawValue
payload.append(b1)
if data.count <= 125 {
b2 |= UInt8(data.count)
payload.append(b2)
} else if data.count >= 126 && data.count <= 65535 {
b2 |= 126
payload.append(b2)
payload.append(contentsOf: UInt16(data.count).toNetwork())
} else {
b2 |= 127
payload.append(b2)
payload.append(contentsOf: UInt64(data.count).toNetwork())
}
payload.append(contentsOf: data)
sendq.append((opcode, payload))
}
func log(_ s: String) {
print("[BRWebSocket \(fd)] \(s)")
}
}
extension UInt16 {
func toNetwork() -> [UInt8] {
var selfBig = CFSwapInt16HostToBig(self)
let size = MemoryLayout<UInt16>.size
return Data(bytes: &selfBig, count: size).withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> [UInt8] in
return Array(UnsafeBufferPointer(start: p, count: size))
})
}
}
extension UInt64 {
func toNetwork() -> [UInt8] {
var selfBig = CFSwapInt64HostToBig(self)
let size = MemoryLayout<UInt64>.size
return Data(bytes: &selfBig, count: size).withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> [UInt8] in
return Array(UnsafeBufferPointer(start: p, count: size))
})
}
}
| 45e028cdeae88b403c780e833648147b | 36.969072 | 134 | 0.490943 | false | false | false | false |
daher-alfawares/Chart | refs/heads/master | Chart/CompoundBar.swift | apache-2.0 | 1 | //
// CompoundBar.swift
// Chart
//
// Created by Daher Alfawares on 4/18/16.
// Copyright © 2016 Daher Alfawares. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
@IBDesignable class CompoundBar : UIView {
@IBInspectable var v1 : CGFloat = CGFloat(100)
@IBInspectable var C1 : UIColor = UIColor.blue
@IBInspectable var v2 : CGFloat = CGFloat(100)
@IBInspectable var C2 : UIColor = UIColor.green
@IBInspectable var v3 : CGFloat = CGFloat(100)
@IBInspectable var C3 : UIColor = UIColor.orange
@IBInspectable var v4 : CGFloat = CGFloat(100)
@IBInspectable var C4 : UIColor = UIColor.gray
@IBInspectable var v5 : CGFloat = CGFloat(100)
@IBInspectable var C5 : UIColor = UIColor.magenta
@IBInspectable var seperator = CGFloat(2)
override func draw(_ rect: CGRect) {
super.draw(rect)
if (current == nil) {
current = [Double(v1),Double(v2),Double(v3),Double(v4),Double(v5)]
}
let calculator = CompoundBarChartCalculator(
Values: current!,
Height: Double(rect.size.height),
Seperator: Double(seperator)
)
let colors = [C1,C2,C3,C4,C5]
let x0 = Double(0)
let x1 = Double(rect.size.width)
for (index,bar) in calculator.bars().enumerated() {
let path = UIBezierPath()
path.move( to: CGPoint(x: x0, y: bar.start))
path.addLine(to: CGPoint(x: x1, y: bar.start))
path.addLine(to: CGPoint(x: x1, y: bar.end))
path.addLine(to: CGPoint(x: x0, y: bar.end))
colors[index%colors.count].setFill()
path.fill()
}
}
// Animations
fileprivate var current : [Double]?
fileprivate var target : [Double]?
fileprivate var displayLink : CADisplayLink!
fileprivate var original : [Double]?
fileprivate var startTime : TimeInterval = 0
fileprivate var duration : TimeInterval = 2
func setValues(_ values:[Double], animated:Bool){
if animated, let _ = current {
original = current!
target = values
while current?.count < target?.count {
current?.append(0)
}
displayLink = CADisplayLink(target: self, selector: #selector(CompoundBar.animateMe))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
startTime = 0
} else {
current = values
}
setNeedsDisplay()
}
func animateMe(){
guard startTime > 0 else {
startTime = displayLink.timestamp
return
}
let t1 = self.startTime
let t2 = displayLink.timestamp
let dt = t2 - t1
if dt > duration {
displayLink?.invalidate()
return
}
let r = Double( dt / duration )
var c = [Double]()
for (i,_) in target!.enumerated() {
let Ci = current?[i] ?? 0
let Ti = target![i]
let Vi = Ci + r * ( Ti - Ci )
c.append(Vi)
}
current = c
setNeedsDisplay()
}
}
| 6a1c06efc99cf6df47804dde18aeb0b4 | 26.787402 | 97 | 0.534429 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCFittingAmmoViewController.swift | lgpl-2.1 | 2 | //
// NCFittingAmmoViewController.swift
// Neocom
//
// Created by Artem Shimanski on 01.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import Dgmpp
import EVEAPI
import Futures
class NCAmmoNode: NCFetchedResultsObjectNode<NCDBInvType> {
required init(object: NCDBInvType) {
super.init(object: object)
self.cellIdentifier = object.dgmppItem?.damage == nil ? Prototype.NCDefaultTableViewCell.compact.reuseIdentifier : Prototype.NCChargeTableViewCell.default.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
if let cell = cell as? NCChargeTableViewCell {
cell.titleLabel?.text = object.typeName
cell.iconView?.image = object.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image
cell.object = object
if let damage = object.dgmppItem?.damage {
var total = damage.emAmount + damage.kineticAmount + damage.thermalAmount + damage.explosiveAmount
if total == 0 {
total = 1
}
cell.emLabel.progress = damage.emAmount / total
cell.emLabel.text = NCUnitFormatter.localizedString(from: damage.emAmount, unit: .none, style: .short)
cell.kineticLabel.progress = damage.kineticAmount / total
cell.kineticLabel.text = NCUnitFormatter.localizedString(from: damage.kineticAmount, unit: .none, style: .short)
cell.thermalLabel.progress = damage.thermalAmount / total
cell.thermalLabel.text = NCUnitFormatter.localizedString(from: damage.thermalAmount, unit: .none, style: .short)
cell.explosiveLabel.progress = damage.explosiveAmount / total
cell.explosiveLabel.text = NCUnitFormatter.localizedString(from: damage.explosiveAmount, unit: .none, style: .short)
}
else {
for label in [cell.emLabel, cell.kineticLabel, cell.thermalLabel, cell.explosiveLabel] {
label?.progress = 0
label?.text = "0"
}
}
}
else if let cell = cell as? NCDefaultTableViewCell {
cell.titleLabel?.text = object.typeName
cell.iconView?.image = object.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image
cell.object = object
cell.accessoryType = .detailButton
}
}
}
class NCAmmoSection: FetchedResultsNode<NCDBInvType> {
init?(category: NCDBDgmppItemCategory, objectNode: NCFetchedResultsObjectNode<NCDBInvType>.Type) {
guard let context = NCDatabase.sharedDatabase?.viewContext else {return nil}
guard let group: NCDBDgmppItemGroup = NCDatabase.sharedDatabase?.viewContext.fetch("DgmppItemGroup", where: "category == %@ AND parentGroup == NULL", category) else {return nil}
let request = NSFetchRequest<NCDBInvType>(entityName: "InvType")
request.predicate = NSPredicate(format: "dgmppItem.groups CONTAINS %@", group)
request.sortDescriptors = [
NSSortDescriptor(key: "metaGroup.metaGroupID", ascending: true),
NSSortDescriptor(key: "metaLevel", ascending: true),
NSSortDescriptor(key: "typeName", ascending: true)]
let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: "metaGroup.metaGroupID", cacheName: nil)
super.init(resultsController: controller, sectionNode: NCMetaGroupFetchedResultsSectionNode<NCDBInvType>.self, objectNode: objectNode)
}
}
class NCFittingAmmoViewController: NCTreeViewController {
var category: NCDBDgmppItemCategory?
var completionHandler: ((NCFittingAmmoViewController, NCDBInvType?) -> Void)!
var modules: [DGMModule]?
override func viewDidLoad() {
super.viewDidLoad()
let module = modules?.first
if module?.charge == nil {
self.navigationItem.rightBarButtonItem = nil
}
tableView.register([Prototype.NCActionTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact,
Prototype.NCHeaderTableViewCell.default,
Prototype.NCChargeTableViewCell.default])
}
override func content() -> Future<TreeNode?> {
guard let category = category else {return .init(nil)}
guard let group: NCDBDgmppItemGroup = NCDatabase.sharedDatabase?.viewContext.fetch("DgmppItemGroup", where: "category == %@ AND parentGroup == NULL", category) else {return .init(nil)}
title = group.groupName
guard let ammo = NCAmmoSection(category: category, objectNode: NCAmmoNode.self) else {return .init(nil)}
let root = TreeNode()
try? ammo.resultsController.performFetch()
let dealsDamage = ammo.resultsController.fetchedObjects?.first?.dgmppItem?.damage != nil
if dealsDamage {
let route = Router.Fitting.AmmoDamageChart(category: category, modules: modules ?? [])
root.children = [NCActionRow(title: NSLocalizedString("Compare", comment: ""), route: route), ammo]
}
else {
root.children = [ammo]
}
return .init(root)
}
@IBAction func onClear(_ sender: Any) {
completionHandler(self, nil)
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
if let node = node as? NCAmmoNode {
completionHandler(self, node.object)
}
}
override func treeController(_ treeController: TreeController, accessoryButtonTappedWithNode node: TreeNode) {
super.treeController(treeController, accessoryButtonTappedWithNode: node)
guard let node = node as? NCAmmoNode else {return}
Router.Database.TypeInfo(node.object).perform(source: self, sender: treeController.cell(for: node))
}
//MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "NCDatabaseTypeInfoViewController"?:
guard let controller = segue.destination as? NCDatabaseTypeInfoViewController,
let cell = sender as? NCTableViewCell,
let type = cell.object as? NCDBInvType else {
return
}
controller.type = type
default:
break
}
}
}
| a5e3d513cd4a72dd183da5adbb1ef6a4 | 35.7875 | 186 | 0.738532 | false | false | false | false |
EZ-NET/ESSwim | refs/heads/swift-2.2 | Sources/Function/Sequence.swift | mit | 1 | //
// Sequence.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/06/10.
//
//
extension SequenceType where Self.Generator.Element : Equatable {
/**
Returns the first index where `value` appears in `domain` or `nil` if `value` is not found.
*/
public func findElement(value:Self.Generator.Element) -> EnumerateSequence<Self>.Generator.Element? {
return self.findElement {
$0 == value
}
}
}
extension SequenceType {
/**
Processing each value of `domain` with `predicate` in order.
If predicate returns .Abort, abort processing and return .Aborted.
If you want index of element, use this function with enumerate(sequence) as `S`.
:return: .Passed if all elements processed, otherwise .Aborted.
*/
public func traverse(@noescape predicate:(Self.Generator.Element) -> Swim.ContinuousState) -> Swim.ProcessingState {
for element in self {
if predicate(element) == .Abort {
return .Aborted
}
}
return .Passed
}
/**
Processing each value of `domain` with `predicate` in order.
If predicate returns non-nil value, abort processing and return the result value.
:return: result of `predicate` if `predicate` results non-nil value, otherwise nil.
*/
public func traverse<R>(@noescape predicate:(Self.Generator.Element) -> R?) -> R? {
for element in self {
if let result = predicate(element) {
return result
}
}
return nil
}
/**
Returns the first index where `predicate` become true in `domain` or `nil` if `value` is not found.
*/
public func findElement(predicate:(Self.Generator.Element) -> Bool) -> EnumerateSequence<Self>.Generator.Element? {
var result:EnumerateSequence<Self>.Generator.Element?
let abortIfFound = { (enumerated:EnumerateSequence<Self>.Generator.Element) -> Swim.ContinuousState in
if predicate(enumerated.element) {
result = enumerated
return .Abort
}
else {
return .Continue
}
}
self.enumerate().traverse(abortIfFound)
return result
}
}
| 5c460c30f155327d05a7d93fc3b3c879 | 22.604651 | 117 | 0.683251 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/TitleSwitch/TitleSwitchCell.swift | mit | 1 | //
// TitleSwitchCell.swift
// Yep
//
// Created by NIX on 16/6/6.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
class TitleSwitchCell: UITableViewCell {
var toggleSwitchStateChangedAction: ((on: Bool) -> Void)?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.blackColor()
label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight)
label.text = "Title"
return label
}()
lazy var toggleSwitch: UISwitch = {
let s = UISwitch()
s.addTarget(self, action: #selector(TitleSwitchCell.toggleSwitchStateChanged(_:)), forControlEvents: .ValueChanged)
return s
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
makeUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func toggleSwitchStateChanged(sender: UISwitch) {
toggleSwitchStateChangedAction?(on: sender.on)
}
private func makeUI() {
contentView.addSubview(titleLabel)
contentView.addSubview(toggleSwitch)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
toggleSwitch.translatesAutoresizingMaskIntoConstraints = false
let views = [
"titleLable": titleLabel,
"toggleSwitch": toggleSwitch,
]
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[titleLable]-[toggleSwitch]-20-|", options: [.AlignAllCenterY], metrics: nil, views: views)
let centerY = titleLabel.centerYAnchor.constraintEqualToAnchor(contentView.centerYAnchor)
NSLayoutConstraint.activateConstraints(constraintsH)
NSLayoutConstraint.activateConstraints([centerY])
}
}
| bea389b0f66c819b84ecd39e9ed39554 | 28.2 | 173 | 0.678609 | false | false | false | false |
benlangmuir/swift | refs/heads/master | SwiftCompilerSources/Sources/Optimizer/DataStructures/BasicBlockWorklist.swift | apache-2.0 | 2 | //===--- BasicBlockWorklist.swift - a worklist of basic block -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// A utility for processing basic blocks in a worklist.
///
/// A `BasicBlockWorklist` is basically a combination of a block array and a block set.
/// It can be used for typical worklist-processing algorithms.
///
/// This type should be a move-only type, but unfortunately we don't have move-only
/// types yet. Therefore it's needed to call `deinitialize()` explicitly to
/// destruct this data structure, e.g. in a `defer {}` block.
struct BasicBlockWorklist : CustomStringConvertible, CustomReflectable {
private var worklist: Stack<BasicBlock>
private var pushedBlocks: BasicBlockSet
init(_ context: PassContext) {
self.worklist = Stack(context)
self.pushedBlocks = BasicBlockSet(context)
}
/// Pops the last added block from the worklist or returns nil, if the worklist is empty.
mutating func pop() -> BasicBlock? { return worklist.pop() }
/// Pushes \p block onto the worklist if \p block has never been pushed before.
mutating func pushIfNotVisited(_ block: BasicBlock) {
if pushedBlocks.insert(block) {
worklist.append(block)
}
}
/// Pushes all elements of \p contentsOf which have never been pushed before.
mutating func pushIfNotVisited<S: Sequence>(contentsOf other: S) where S.Element == BasicBlock {
for block in other {
pushIfNotVisited(block)
}
}
/// Returns true if \p block was pushed to the worklist, regardless if it's already popped or not.
func hasBeenPushed(_ block: BasicBlock) -> Bool { pushedBlocks.contains(block) }
var description: String {
"""
worklist: \(worklist)
pushed: \(pushedBlocks)
"""
}
var customMirror: Mirror { Mirror(self, children: []) }
/// TODO: once we have move-only types, make this a real deinit.
mutating func deinitialize() {
pushedBlocks.deinitialize()
worklist.deinitialize()
}
}
| 9771e0e2cb0e66f61250e05416ee0536 | 35.090909 | 100 | 0.680521 | false | false | false | false |
gaintext/gaintext-engine | refs/heads/master | Sources/Engine/Line.swift | gpl-3.0 | 1 | //
// GainText parser
// Copyright Martin Waitz
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
import Runes
public func textWithMarkupParser(markup: Parser<[Node]>) -> SpanParser {
return { endMarker in
Parser { input in
var startOfText = input.position
var cursor = input
let element = input.element
do { // immediately return when endMarker matches
return try (endMarker *> pure([])).parse(cursor)
} catch is ParserError {}
var nodes: [Node] = []
func addTextNode() {
if cursor.position != startOfText {
let text = textNode(start: startOfText, end: cursor)
nodes.append(text)
}
}
cursor.markStartOfWord()
while !cursor.atEndOfLine {
do {
let (markupNodes, nextCursor) = try markup.parse(cursor)
addTextNode()
nodes += markupNodes
cursor = nextCursor
startOfText = cursor.position
} catch {
try! cursor.advance()
}
do {
let (_, tail) = try endMarker.parse(cursor)
addTextNode()
assert(tail.element === element)
return (nodes, tail)
} catch is ParserError {}
}
throw ParserError.notFound(position: cursor.position)
}
}
}
public func rawTextParser(endMarker: Parser<()>) -> Parser<[Node]> {
return Parser { input in
let startOfText = input.position
var cursor = input
while !cursor.atEndOfLine {
do {
let (_, tail) = try endMarker.parse(cursor)
guard cursor.position != startOfText else {
return ([], tail)
}
let text = textNode(start: startOfText, end: cursor)
return ([text], tail)
} catch is ParserError {
try! cursor.advance()
}
}
throw ParserError.notFound(position: cursor.position)
}
}
/// Parse one complete line using the current span parser
public let lineParser = Parser<[Node]> { input in
guard !input.atEndOfBlock else {
throw ParserError.notFound(position: input.position)
}
return try input.scope.spanParser(satisfying {$0.atEndOfLine}).parse(input)
}
| 9d8c7753654a3bac6432a35d50848d06 | 31.282353 | 79 | 0.532799 | false | false | false | false |
jobandtalent/AnimatedTextInput | refs/heads/master | AnimatedTextInput/Classes/AnimatedTextInputStyle.swift | mit | 1 | import UIKit
public protocol AnimatedTextInputStyle {
var activeColor: UIColor { get }
var placeholderInactiveColor: UIColor { get }
var inactiveColor: UIColor { get }
var lineInactiveColor: UIColor { get }
var lineActiveColor: UIColor { get }
var lineHeight: CGFloat { get }
var errorColor: UIColor { get }
var textInputFont: UIFont { get }
var textInputFontColor: UIColor { get }
var placeholderMinFontSize: CGFloat { get }
var counterLabelFont: UIFont? { get }
var leftMargin: CGFloat { get }
var topMargin: CGFloat { get }
var rightMargin: CGFloat { get }
var bottomMargin: CGFloat { get }
var yHintPositionOffset: CGFloat { get }
var yPlaceholderPositionOffset: CGFloat { get }
var textAttributes: [String: Any]? { get }
}
public struct AnimatedTextInputStyleBlue: AnimatedTextInputStyle {
private static let customBlue = UIColor(red: 51.0/255.0, green: 175.0/255.0, blue: 236.0/255.0, alpha: 1.0)
public let activeColor = AnimatedTextInputStyleBlue.customBlue
public let placeholderInactiveColor = UIColor.gray.withAlphaComponent(0.5)
public let inactiveColor = UIColor.gray.withAlphaComponent(0.5)
public let lineInactiveColor = UIColor.gray.withAlphaComponent(0.2)
public let lineActiveColor = AnimatedTextInputStyleBlue.customBlue.withAlphaComponent(0.5)
public let lineHeight: CGFloat = 1.0 / UIScreen.main.scale
public let errorColor = UIColor.red
public let textInputFont = UIFont.systemFont(ofSize: 14)
public let textInputFontColor = UIColor.black
public let placeholderMinFontSize: CGFloat = 9
public let counterLabelFont: UIFont? = UIFont.systemFont(ofSize: 9)
public let leftMargin: CGFloat = 25
public let topMargin: CGFloat = 20
public let rightMargin: CGFloat = 0
public let bottomMargin: CGFloat = 10
public let yHintPositionOffset: CGFloat = 7
public let yPlaceholderPositionOffset: CGFloat = 0
//Text attributes will override properties like textInputFont, textInputFontColor...
public let textAttributes: [String: Any]? = nil
public init() { }
}
| 20433d23082909831407198cd81040cc | 44.297872 | 111 | 0.73086 | false | false | false | false |
alblue/swift | refs/heads/master | test/SILGen/metatype_abstraction.swift | apache-2.0 | 2 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership -module-name Swift -parse-stdlib %s | %FileCheck %s
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {}
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
struct S {}
class C {}
struct Generic<T> {
var value: T
}
struct GenericMetatype<T> {
var value: T.Type
}
// CHECK-LABEL: sil hidden @$ss26genericMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<T.Type>, #Generic.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick T.Type
// CHECK: return [[META]] : $@thick T.Type
// CHECK: }
func genericMetatypeFromGeneric<T>(_ x: Generic<T.Type>) -> T.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden @$ss26dynamicMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<C.Type>, #Generic.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick C.Type
// CHECK: return [[META]] : $@thick C.Type
// CHECK: }
func dynamicMetatypeFromGeneric(_ x: Generic<C.Type>) -> C.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden @$ss25staticMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[META:%.*]] = metatype $@thin S.Type
// CHECK: return [[META]] : $@thin S.Type
// CHECK: }
func staticMetatypeFromGeneric(_ x: Generic<S.Type>) -> S.Type {
return x.value
}
// CHECK-LABEL: sil hidden @$ss026genericMetatypeFromGenericB0{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*GenericMetatype<T>, #GenericMetatype.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick T.Type
// CHECK: return [[META]] : $@thick T.Type
// CHECK: }
func genericMetatypeFromGenericMetatype<T>(_ x: GenericMetatype<T>)-> T.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden @$ss026dynamicMetatypeFromGenericB0ys1CCms0dB0VyACGF
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var GenericMetatype<C> }
// CHECK: [[PX:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*GenericMetatype<C>
// CHECK: [[ADDR:%.*]] = struct_element_addr [[READ]] : $*GenericMetatype<C>, #GenericMetatype.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick C.Type
// CHECK: return [[META]] : $@thick C.Type
// CHECK: }
func dynamicMetatypeFromGenericMetatype(_ x: GenericMetatype<C>) -> C.Type {
var x = x
return x.value
}
func takeGeneric<T>(_ x: T) {}
func takeGenericMetatype<T>(_ x: T.Type) {}
// CHECK-LABEL: sil hidden @$ss23staticMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick S.Type
// CHECK: [[META:%.*]] = metatype $@thick S.Type
// CHECK: store [[META]] to [trivial] [[MAT]] : $*@thick S.Type
// CHECK: apply {{%.*}}<S.Type>([[MAT]])
func staticMetatypeToGeneric(_ x: S.Type) {
takeGeneric(x)
}
// CHECK-LABEL: sil hidden @$ss023staticMetatypeToGenericB0{{[_0-9a-zA-Z]*}}F
// CHECK: [[META:%.*]] = metatype $@thick S.Type
// CHECK: apply {{%.*}}<S>([[META]])
func staticMetatypeToGenericMetatype(_ x: S.Type) {
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden @$ss24dynamicMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick C.Type
// CHECK: apply {{%.*}}<C.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> ()
func dynamicMetatypeToGeneric(_ x: C.Type) {
var x = x
takeGeneric(x)
}
// CHECK-LABEL: sil hidden @$ss024dynamicMetatypeToGenericB0yys1CCmF
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var @thick C.Type }
// CHECK: [[PX:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*@thick C.Type
// CHECK: [[META:%.*]] = load [trivial] [[READ]] : $*@thick C.Type
// CHECK: apply {{%.*}}<C>([[META]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> ()
func dynamicMetatypeToGenericMetatype(_ x: C.Type) {
var x = x
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden @$ss24genericMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick U.Type
// CHECK: apply {{%.*}}<U.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> ()
func genericMetatypeToGeneric<U>(_ x: U.Type) {
var x = x
takeGeneric(x)
}
func genericMetatypeToGenericMetatype<U>(_ x: U.Type) {
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden @$ss019static_metatype_of_B0ys1SVmmACF
// CHECK: metatype $@thin S.Type.Type
func static_metatype_of_metatype(_ x: S) -> S.Type.Type {
return type(of: type(of: x))
}
// CHECK-LABEL: sil hidden @$ss018class_metatype_of_B0ys1CCmmACF
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick C.Type
// CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick C.Type.Type, [[METATYPE]]
func class_metatype_of_metatype(_ x: C) -> C.Type.Type {
return type(of: type(of: x))
}
// CHECK-LABEL: sil hidden @$ss020generic_metatype_of_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick T.Type
// CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick T.Type.Type, [[METATYPE]]
func generic_metatype_of_metatype<T>(_ x: T) -> T.Type.Type {
return type(of: type(of: x))
}
// FIXME rdar://problem/18419772
/*
func existential_metatype_of_metatype(_ x: Any) -> Any.Type.Type {
return type(of: type(of: x))
}
*/
func function_metatype_of_metatype(_ x: @escaping () -> ()) -> (() -> ()).Type.Type {
return type(of: type(of: x))
}
| f875d07166c06f4eb48c505be8e0d9d5 | 38.303448 | 108 | 0.592736 | false | false | false | false |
pkx0128/UIKit | refs/heads/master | MTabBarAndNav/MTabBarAndNav/Class/Main/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// MTabBarAndNav
//
// Created by pankx on 2017/9/29.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// setupChild()
childNav()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MainViewController {
func setupChild() {
let home = HomeViewController()
home.title = "首页"
home.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tabbar_home"), selectedImage: UIImage(named: "tabbar_home_seleted"))
let homeNav = NavViewController(rootViewController: home)
let message = MessageViewController()
message.title = "信息"
message.tabBarItem = UITabBarItem(title: "Message", image: UIImage(named: "tabbar_message_center"), selectedImage: UIImage(named: "tabbar_message_center_seleted"))
let messageNav = NavViewController(rootViewController: message)
let discover = DisCoverViewController()
discover.title = "发现"
discover.tabBarItem = UITabBarItem(title: "Discover", image: UIImage(named: "tabbar_discover"), selectedImage: UIImage(named: "tabbar_discover_seleted"))
let discoverNav = NavViewController(rootViewController: discover)
let profile = ProfileViewController()
profile.title = "我"
profile.tabBarItem = UITabBarItem(title: "Me", image: UIImage(named: "tabbar_profile"), selectedImage: UIImage(named: "tabbar_profile_seleted"))
let profileNav = NavViewController(rootViewController: profile)
self.viewControllers = [homeNav,messageNav,discoverNav,profileNav]
}
func getnavview(dit:[String:String]) -> UIViewController {
guard let clsstr = dit["className"] ,let title = dit["title"], let image = dit["image"], let selectedImage = dit["selectedImage"] else {
return UIViewController()
}
let ns = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
let clsn = ns + "." + clsstr
let cls = NSClassFromString(clsn) as! BaseViewController.Type
let vc = cls.init()
vc.title = title
vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .selected)
vc.tabBarItem.image = UIImage(named: image)
vc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.withRenderingMode(.alwaysOriginal)
let nav = NavViewController(rootViewController: vc)
return nav
}
func childNav() {
let NavInfo = [["className":"HomeViewController","title": "首页","image": "tabbar_home","selectedImage":"tabbar_home_selected"],
["className":"MessageViewController","title": "信息","image": "tabbar_message_center","selectedImage":"tabbar_message_center_selected"],
["className":"DisCoverViewController","title": "发现","image": "tabbar_discover","selectedImage":"tabbar_discover_selected"],
["className":"ProfileViewController","title": "我","image": "tabbar_profile","selectedImage":"tabbar_profile_selected"]]
var NavArr = [UIViewController]()
for nav in NavInfo {
NavArr.append(getnavview(dit: nav))
}
self.viewControllers = NavArr
}
}
| 22122a05bbdee74c80e5b0ba5950b241 | 42.530864 | 171 | 0.650312 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Classes/Old UI/IntroViewController.swift | gpl-3.0 | 1 | //
// IntroViewController.swift
// iSub Beta
//
// Created by Benjamin Baron on 7/2/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
import AVKit
class IntroViewController: UIViewController {
@IBOutlet weak var introVideo: UIButton!
@IBOutlet weak var testServer: UIButton!
@IBOutlet weak var ownServer: UIButton!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var shouldAutorotate: Bool {
return true
}
@IBAction func buttonPress(_ sender: UIButton) {
if sender == introVideo {
let introUrl: URL?
if UIScreen.main.scale > 1.0 {
introUrl = URL(string: "http://isubapp.com/intro/iphone4/prog_index.m3u8")
} else {
introUrl = URL(string: "http://isubapp.com/intro/iphone/prog_index.m3u8")
}
if let introUrl = introUrl {
let playerViewController = AVPlayerViewController()
playerViewController.player = AVPlayer(url: introUrl)
self.present(playerViewController, animated: true) {
playerViewController.player?.play()
}
}
} else if sender == testServer {
self.dismiss(animated: true, completion: nil)
} else if sender == ownServer {
self.dismiss(animated: true, completion: nil)
if let menu = AppDelegate.si.sidePanelController.leftPanel as? MenuViewController {
menu.showSettings()
}
}
}
}
| d2fd9919f5b9b0d507d43a219e32832b | 31.52 | 95 | 0.591636 | false | false | false | false |
plivesey/SwiftGen | refs/heads/master | swiftgen-cli/colors.swift | mit | 1 | //
// SwiftGen
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Commander
import PathKit
import GenumKit
import Stencil
let colorsCommand = command(
outputOption,
templateOption(prefix: "colors"), templatePathOption,
Option<String>("enumName", "ColorName", flag: "e", description: "The name of the enum to generate"),
Argument<Path>("FILE", description: "Colors.txt|.clr|.xml|.json file to parse.", validator: fileExists)
) { output, templateName, templatePath, enumName, path in
let parser: ColorsFileParser
switch path.extension {
case "clr"?:
let clrParser = ColorsCLRFileParser()
try clrParser.parseFile(at: path)
parser = clrParser
case "txt"?:
let textParser = ColorsTextFileParser()
try textParser.parseFile(at: path)
parser = textParser
case "xml"?:
let textParser = ColorsXMLFileParser()
try textParser.parseFile(at: path)
parser = textParser
case "json"?:
let textParser = ColorsJSONFileParser()
try textParser.parseFile(at: path)
parser = textParser
default:
throw ArgumentError.invalidType(value: path.description, type: "CLR, TXT, XML or JSON file", argument: nil)
}
do {
let templateRealPath = try findTemplate(
prefix: "colors", templateShortName: templateName, templateFullPath: templatePath
)
let template = try GenumTemplate(templateString: templateRealPath.read(), environment: genumEnvironment())
let context = parser.stencilContext(enumName: enumName)
let rendered = try template.render(context)
output.write(content: rendered, onlyIfChanged: true)
} catch {
printError(string: "error: failed to render template \(error)")
}
}
| 74985d1b8f0e5263fab9a3ff765d0ff5 | 31.365385 | 111 | 0.717766 | false | false | false | false |
automationWisdri/WISData.JunZheng | refs/heads/master | WISData.JunZheng/Model/MaterialPower.swift | mit | 1 | //
// MaterialPower.swift
// WISData.JunZheng
//
// Created by Allen on 16/8/22.
// Copyright © 2016 Wisdri. All rights reserved.
//
import Alamofire
import SwiftyJSON
import MJExtension
class MaterialPower: NSObject, PropertyNames {
/// 工艺电
var GYD: String?
var BQCL: String?
var JHHZL: String?
var JTZH: String?
var LTGDT: String?
var LTHF: String?
var LTHFF: String?
var LTSF: String?
var LTZH: String?
var PJPB: String?
var SHCaO: String?
var SHGS: String?
var SHSS: String?
var SHZH: String?
var WYMGDT: String?
var WYMHF: String?
var WYMHFF: String?
var WYMSF: String?
var WYMZH: String?
var YQPS: String?
var YQZL: String?
var Remark: String?
var SwithTimeReasons: SwitchTimeReason?
}
class SwitchTimeReason: NSObject, PropertyNames {
var CutHour: String?
var CutMinute: String?
var OnHour: String?
var OnMinute: String?
var Reason: String?
}
class DailyMaterialPower: NSObject, PropertyNames {
var GYD: String?
var BQCL: String?
var JHHZL: String?
var LTZH: String?
var WYMZH: String?
var PJPB: String?
var JTZH: String?
var SHZH: String?
var YQPS: String?
var YQZL: String?
}
extension MaterialPower {
class func get(date date: String, shiftNo: String, lNo: String, completionHandler: WISValueResponse<JSON> -> Void) -> Void {
let getURL = BaseURL + "/GetMaterialPower?date=\(date)&shiftNo=\(shiftNo)&lNo=\(lNo)"
HTTPManager.sharedInstance.request(.POST, getURL).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
// debugPrint("JSON: \(json)")
// debugPrint(json.rawString())
guard json["Result"] == 1 else {
let t = WISValueResponse<JSON>(value: JSON.null, success: false)
t.message = "未检索到所需数据, \n请修改查询条件后重试。"
completionHandler(t)
return
}
// switchCount is one by default
var switchCount = 1
if let str = SwitchTimeReason.mj_objectArrayWithKeyValuesArray(json["SwithTimeReasons"].rawString()!) {
switchCount = str.count
}
let t = WISValueResponse<JSON>(value: json, success: true)
completionHandler(t)
}
case .Failure(let error):
debugPrint(error)
debugPrint("\nError Description: " + error.localizedDescription)
let t = WISValueResponse<JSON>(value: JSON.null, success: false)
t.message = error.localizedDescription + "\n请检查设备的网络设置, 然后下拉页面刷新。"
completionHandler(t)
}
}
}
}
extension DailyMaterialPower {
class func get(date date: String, lNo: String, completionHandler: WISValueResponse<JSON> -> Void) -> Void {
let getURL = BaseURL + "/GetDailyMateralPower?date=\(date)&lNo=\(lNo)"
HTTPManager.sharedInstance.request(.POST, getURL).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
guard json["Result"] == 1 else {
let t = WISValueResponse<JSON>(value: JSON.null, success: false)
t.message = "未检索到所需数据, \n请修改查询条件后重试。"
completionHandler(t)
return
}
// let dailyMaterialPower = DailyMaterialPower.mj_objectWithKeyValues(json.rawString())
// for p in DailyMaterialPower().propertyNames() {
// debugPrint(p)
// }
//
// debugPrint(dailyMaterialPower.PJPB)
let t = WISValueResponse<JSON>(value: json, success: true)
completionHandler(t)
}
case .Failure(let error):
debugPrint(error)
debugPrint("\nError Description: " + error.localizedDescription)
let t = WISValueResponse<JSON>(value: JSON.null, success: false)
t.message = error.localizedDescription + "\n请检查设备的网络设置, 然后下拉页面刷新。"
completionHandler(t)
}
}
}
}
| 1e3c578cb8e8071c5d65bd9e631df3df | 32.208333 | 128 | 0.529904 | false | false | false | false |
byvapps/ByvUtils | refs/heads/master | ByvUtils/Classes/UIImage+extension.swift | mit | 1 | //
// UIImage+extension.swift
// Pods
//
// Created by Adrian Apodaca on 17/2/17.
//
//
import Foundation
public extension UIImage {
/// Returns a image that fills in newSize
func resizedImageToSize(_ newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContext(size)
self.draw(in: CGRect(x:0, y:0, width:size.width, height:size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
/// Returns a resized image that fits in rectSize, keeping it's aspect ratio
/// Note that the new image size is not rectSize, but within it.
func resizedImageToMaxSize(_ maxSize: CGSize) -> UIImage {
let widthFactor = size.width / maxSize.width
let heightFactor = size.height / maxSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width: size.width/resizeFactor, height: size.height/resizeFactor)
let resized = resizedImageToSize(newSize)
return resized
}
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
func alpha(_ value:CGFloat)->UIImage
{
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| d9d95b9a13672e8aaf4ed8036926f8cc | 31.888889 | 94 | 0.640927 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Edit data/Delete features (feature service)/DeleteFeaturesViewController.swift | apache-2.0 | 1 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class DeleteFeaturesViewController: UIViewController, AGSGeoViewTouchDelegate, AGSCalloutDelegate {
@IBOutlet var mapView: AGSMapView! {
didSet {
mapView.map = AGSMap(basemapStyle: .arcGISStreets)
// Set touch delegate on map view as self.
mapView.touchDelegate = self
mapView.callout.delegate = self
}
}
/// The feature table to delete features from.
var featureTable: AGSServiceFeatureTable!
/// The service geodatabase that contains damaged property features.
var serviceGeodatabase: AGSServiceGeodatabase!
/// The feature layer created from the feature table.
var featureLayer: AGSFeatureLayer!
/// Last identify operation.
var lastQuery: AGSCancelable!
/// The currently selected feature.
var selectedFeature: AGSFeature!
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["DeleteFeaturesViewController"]
// Load the service geodatabase.
let damageFeatureService = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer")!
loadServiceGeodatabase(from: damageFeatureService)
}
/// Load and set a service geodatabase from a feature service URL.
/// - Parameter serviceURL: The URL to the feature service.
func loadServiceGeodatabase(from serviceURL: URL) {
let serviceGeodatabase = AGSServiceGeodatabase(url: serviceURL)
serviceGeodatabase.load { [weak self] error in
guard let self = self else { return }
if let error = error {
self.presentAlert(error: error)
} else {
let featureTable = serviceGeodatabase.table(withLayerID: 0)!
self.featureTable = featureTable
self.serviceGeodatabase = serviceGeodatabase
// Add the feature layer to the operational layers on map.
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
self.featureLayer = featureLayer
self.mapView.map?.operationalLayers.add(featureLayer)
self.mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: 544871.19, y: 6806138.66, spatialReference: .webMercator()), scale: 2e6))
}
}
}
func showCallout(for feature: AGSFeature, at tapLocation: AGSPoint) {
let title = feature.attributes["typdamage"] as! String
mapView.callout.title = title
mapView.callout.accessoryButtonImage = UIImage(named: "Discard")
mapView.callout.show(for: feature, tapLocation: tapLocation, animated: true)
}
/// Delete a feature from the feature table.
func deleteFeature(_ feature: AGSFeature) {
featureTable.delete(feature) { [weak self] error in
if let error = error {
self?.presentAlert(message: "Error while deleting feature: \(error.localizedDescription)")
} else {
self?.applyEdits()
}
}
}
/// Apply local edits to the geodatabase.
func applyEdits() {
guard serviceGeodatabase.hasLocalEdits() else { return }
serviceGeodatabase.applyEdits { [weak self] _, error in
if let error = error {
self?.presentAlert(message: "Error while applying edits: \(error.localizedDescription)")
}
}
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
if let query = lastQuery { query.cancel() }
// Hide the callout.
mapView.callout.dismiss()
lastQuery = mapView.identifyLayer(featureLayer, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false) { [weak self] identifyLayerResult in
guard let self = self else { return }
self.lastQuery = nil
if let feature = identifyLayerResult.geoElements.first as? AGSFeature {
// Show callout for the feature.
self.showCallout(for: feature, at: mapPoint)
// Update selected feature.
self.selectedFeature = feature
} else if let error = identifyLayerResult.error {
self.presentAlert(error: error)
}
}
}
// MARK: - AGSCalloutDelegate
func didTapAccessoryButton(for callout: AGSCallout) {
mapView.callout.dismiss()
let alertController = UIAlertController(title: "Are you sure you want to delete the feature?", message: nil, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Delete", style: .destructive) { [unowned self] _ in
deleteFeature(selectedFeature)
}
alertController.addAction(alertAction)
let cancelAlertAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(cancelAlertAction)
alertController.preferredAction = cancelAlertAction
present(alertController, animated: true)
}
}
| 0107d6cb3482160d34cfe560feed5caa | 43.090226 | 158 | 0.655355 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Managers/LocalAuthentication/LocalAuthenticationService.swift | apache-2.0 | 1 | //
// Copyright 2020 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@objcMembers
class LocalAuthenticationService: NSObject {
private let pinCodePreferences: PinCodePreferences
init(pinCodePreferences: PinCodePreferences) {
self.pinCodePreferences = pinCodePreferences
super.init()
setup()
}
private var appLastActiveTime: TimeInterval?
private var systemUptime: TimeInterval {
var uptime = timespec()
if 0 != clock_gettime(CLOCK_MONOTONIC_RAW, &uptime) {
fatalError("Could not execute clock_gettime, errno: \(errno)")
}
return TimeInterval(uptime.tv_sec)
}
private func setup() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
}
var shouldShowPinCode: Bool {
if !pinCodePreferences.isPinSet && !pinCodePreferences.isBiometricsSet {
return false
}
if MXKAccountManager.shared()?.activeAccounts.count == 0 {
return false
}
guard let appLastActiveTime = appLastActiveTime else {
return true
}
return (systemUptime - appLastActiveTime) >= pinCodePreferences.graceTimeInSeconds
}
var isProtectionSet: Bool {
return pinCodePreferences.isPinSet || pinCodePreferences.isBiometricsSet
}
func applicationWillResignActive() {
appLastActiveTime = systemUptime
}
func shouldLogOutUser() -> Bool {
if BuildSettings.logOutUserWhenPINFailuresExceeded && pinCodePreferences.numberOfPinFailures >= pinCodePreferences.maxAllowedNumberOfPinFailures {
return true
}
if BuildSettings.logOutUserWhenBiometricsFailuresExceeded && pinCodePreferences.numberOfBiometricsFailures >= pinCodePreferences.maxAllowedNumberOfBiometricsFailures {
return true
}
return false
}
}
| d81dad84015d3218873f92c79b7c75d4 | 32.402597 | 175 | 0.690513 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/NUX/WPStyleGuide+NUX.swift | gpl-2.0 | 1 | import WordPressShared
extension WPStyleGuide {
/// Common view style for signin view controllers.
///
/// - Parameters:
/// - view: The view to style.
///
class func configureColorsForSigninView(_ view: UIView) {
view.backgroundColor = wordPressBlue()
}
/// Adds a 1password button to a WPWalkthroughTextField, if available
///
class func configureOnePasswordButtonForTextfield(_ textField: WPWalkthroughTextField, target: NSObject, selector: Selector) {
if !OnePasswordFacade().isOnePasswordEnabled() {
return
}
let onePasswordButton = UIButton(type: .custom)
onePasswordButton.setImage(UIImage(named: "onepassword-wp-button"), for: UIControlState())
onePasswordButton.sizeToFit()
textField.rightView = onePasswordButton
textField.rightViewPadding = UIOffset(horizontal: 20.0, vertical: 0.0)
textField.rightViewMode = .always
onePasswordButton.addTarget(target, action: selector, for: .touchUpInside)
}
/// Adds a 1password button to a stack view, if available
///
class func configureOnePasswordButtonForStackView(_ stack: UIStackView, target: NSObject, selector: Selector) {
if !OnePasswordFacade().isOnePasswordEnabled() {
return
}
let onePasswordButton = UIButton(type: .custom)
onePasswordButton.setImage(UIImage(named: "onepassword-wp-button"), for: UIControlState())
onePasswordButton.sizeToFit()
onePasswordButton.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
onePasswordButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
stack.addArrangedSubview(onePasswordButton)
onePasswordButton.addTarget(target, action: selector, for: .touchUpInside)
}
///
///
class func colorForErrorView(_ opaque: Bool) -> UIColor {
let alpha: CGFloat = opaque ? 1.0 : 0.95
return UIColor(fromRGBAColorWithRed: 17.0, green: 17.0, blue: 17.0, alpha: alpha)
}
///
///
class func edgeInsetForLoginTextFields() -> UIEdgeInsets {
return UIEdgeInsetsMake(7, 20, 7, 20)
}
/// Return the system font in medium weight for the given style
///
/// - note: iOS won't return UIFontWeightMedium for dynamic system font :(
/// So instead get the dynamic font size, then ask for the non-dynamic font at that size
///
class func mediumWeightFont(forStyle style: UIFontTextStyle) -> UIFont {
let fontToGetSize = WPStyleGuide.fontForTextStyle(style)
return UIFont.systemFont(ofSize: fontToGetSize.pointSize, weight: UIFontWeightMedium)
}
}
| 5713b5adafdf277bbf497fb17036937d | 36.833333 | 130 | 0.685022 | false | false | false | false |
pmlbrito/cookiecutter-ios-template | refs/heads/master | PRODUCTNAME/app/PRODUCTNAME/Presentation/SignIn/Domain/SignInProcess.swift | mit | 1 | //
// SignInProcess.swift
// PRODUCTNAME
//
// Created by LEADDEVELOPER on 06/09/2017.
// Copyright © 2017 ORGANIZATION. All rights reserved.
//
import Foundation
import RxSwift
protocol SignInProcessProtocol {
func getUserCredentials() -> Single<SignInCredentialsProcessResult>
func saveUserCredentials(credentials: SignInUserCredentials) -> Single<BoolProcessResult>
}
class SignInProcess: SignInProcessProtocol {
var defaultsManager: UserDefaultsManager?
var keychainManager: KeyChainAccessManager?
init(userDefaults: UserDefaultsManager?, keychain: KeyChainAccessManager?) {
self.defaultsManager = userDefaults
self.keychainManager = keychain
}
func getUserCredentials() -> Single<SignInCredentialsProcessResult> {
var processResult = SignInCredentialsProcessResult(status: ProcessResult.Status.ok, processMessage: "Saved Credentials Not Found.", resultValue: nil)
if let lastLoginUserName = defaultsManager?.loginUserName {
if let userCredentials = keychainManager?.getUserLoginCredentials(username: lastLoginUserName) {
processResult = SignInCredentialsProcessResult(status: ProcessResult.Status.ok, processMessage: nil, resultValue: userCredentials)
}
}
return Single.just(processResult)
}
func saveUserCredentials(credentials: SignInUserCredentials) -> Single<BoolProcessResult> {
if credentials.userName != nil && credentials.password != nil {
self.defaultsManager?.loginUserName = credentials.userName
self.keychainManager?.saveUserLoginCredentials(credentials: credentials)
return Single.just(BoolProcessResult(status: ProcessResult.Status.ok, resultValue: self.defaultsManager?.loginUserName == credentials.userName && self.keychainManager?.getUserLoginCredentials(username: credentials.userName!) != nil))
}
else {
let error = BoolProcessResult(status: ProcessResult.Status.error, resultValue: false)
error.message = "Invalid Credentials"
return Single.just(error)
}
}
}
| 9e94f7bff285592a6b9428c1d0311dda | 40.745098 | 245 | 0.728981 | false | false | false | false |
yume190/CustomView | refs/heads/master | CustomViewKit/AutoLayoutExtension.swift | mit | 2 | //
// AutoLayoutExtension.swift
// CustomViewTest
//
// Created by Yume on 2015/3/14.
// Copyright (c) 2015年 yume. All rights reserved.
//
import UIKit
public struct LayoutAttribute {
public var view:UIView?
public var attribute:NSLayoutAttribute
public var multiplier:CGFloat
public var constant:CGFloat
init(view:UIView, attribute: NSLayoutAttribute, constant:CGFloat = 0, multiplier:CGFloat = 1.0){
self.view = view;
self.attribute = attribute
self.multiplier = multiplier
self.constant = constant;
}
}
public extension UIView {
func addConstraints (constraints: NSLayoutConstraint...){
for constraint in constraints {
self.addConstraint(constraint)
}
}
public var width : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Width); }
}
public var height : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Height); }
}
public var leading : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Leading); }
}
public var trailing : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Trailing); }
}
public var top : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Top); }
}
public var bottom : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .Bottom); }
}
public var centerX : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .CenterX); }
}
public var centerY : LayoutAttribute {
get { return LayoutAttribute(view: self, attribute : .CenterY); }
}
}
public func == (left: LayoutAttribute, right: LayoutAttribute) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item:left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.Equal, toItem: right.view,
attribute: right.attribute, multiplier: right.multiplier, constant: right.constant)
return layoutConstraint
}
public func >= (left: LayoutAttribute, right: LayoutAttribute) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item: left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: right.view, attribute: right.attribute,
multiplier: right.multiplier, constant: right.constant);
return layoutConstraint
}
public func <= (left: LayoutAttribute, right: LayoutAttribute) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item: left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: right.view, attribute: right.attribute,
multiplier: right.multiplier, constant: right.constant);
return layoutConstraint
}
public func == (left: LayoutAttribute, right: CGFloat) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item:left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.Equal, toItem: nil,
attribute: .NotAnAttribute, multiplier: 1.0, constant: right)
return layoutConstraint
}
public func <= (left: LayoutAttribute, right: CGFloat) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item:left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: nil,
attribute: .NotAnAttribute, multiplier: 1.0, constant: right)
return layoutConstraint
}
public func >= (left: LayoutAttribute, right: CGFloat) -> NSLayoutConstraint {
var layoutConstraint = NSLayoutConstraint(item:left.view!,
attribute: left.attribute, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: nil,
attribute: .NotAnAttribute, multiplier: 1.0, constant: right)
return layoutConstraint
}
// ------------------------------------------
infix operator *+ {
associativity left
precedence 150
}
public func *+(left: LayoutAttribute, right: (multiplier:CGFloat, contant:CGFloat)) -> LayoutAttribute {
var layoutAttribute = LayoutAttribute(view:left.view!, attribute: left.attribute, constant: right.contant, multiplier:right.multiplier)
return layoutAttribute
}
public func *(left: LayoutAttribute, right: CGFloat) -> LayoutAttribute {
var layoutAttribute = LayoutAttribute(view:left.view!, attribute: left.attribute, constant: 0, multiplier:right)
return layoutAttribute
}
public func +(left: LayoutAttribute, right: CGFloat) -> LayoutAttribute {
var layoutAttribute = LayoutAttribute(view:left.view!, attribute: left.attribute, constant: right, multiplier:left.multiplier)
return layoutAttribute
}
public func -(left: LayoutAttribute, right: CGFloat) -> LayoutAttribute {
var layoutAttribute = LayoutAttribute(view:left.view!, attribute: left.attribute, constant: -right, multiplier:left.multiplier)
return layoutAttribute
}
infix operator <~ {
associativity left
precedence 125
}
public func <~ (left: NSLayoutConstraint, right: UILayoutPriority) -> NSLayoutConstraint {
left.priority = right
return left
}
infix operator <- {
associativity right
precedence 90
}
public func <- (left: UIView, right: NSLayoutConstraint) -> UIView {
left.addConstraint(right)
return left
}
| 05f90347cdf2501a74caf42f7c80c237 | 32.886792 | 139 | 0.698961 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | refs/heads/master | UberGo/UberGo/UberProductCell.swift | mit | 1 | //
// UberProductCell.swift
// UberGo
//
// Created by Nghia Tran on 6/18/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Cocoa
import UberGoCore
protocol UberProductCellDelegate: class {
func uberProductCell(_ sender: UberProductCell, shouldShowProductDetail productObj: ProductObj)
}
class UberProductCell: NSCollectionViewItem {
// MARK: - OUTLET
@IBOutlet fileprivate weak var productImageView: NSImageView!
@IBOutlet fileprivate weak var productNameLbl: NSTextField!
@IBOutlet fileprivate weak var priceLbl: NSTextField!
// MARK: - Variable
fileprivate var productObj: ProductObj!
weak var delegate: UberProductCellDelegate?
override var isSelected: Bool {
didSet {
if isSelected {
productImageView.image = NSImage(imageLiteralResourceName: "uber_car_selected")
} else {
productImageView.image = NSImage(imageLiteralResourceName: "uber_car")
}
}
}
// MARK: - Init
override func awakeFromNib() {
super.awakeFromNib()
isSelected = false
initCommon()
}
fileprivate func initCommon() {
productNameLbl.textColor = NSColor.black
priceLbl.textColor = NSColor(hexString: "#555555")
}
// MARK: - Public
public func configureCell(with productObj: ProductObj) {
self.productObj = productObj
// Name
productNameLbl.stringValue = productObj.displayName
// Price
guard let estimatePrice = productObj.estimatePrice else { return }
priceLbl.stringValue = estimatePrice.estimate
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
guard isSelected == true else { return }
delegate?.uberProductCell(self, shouldShowProductDetail: productObj)
}
}
| 5060d04fb0ab43d0e939be2fcb7b75fd | 26.925373 | 99 | 0.664885 | false | false | false | false |
mssun/pass-ios | refs/heads/master | passKit/Protocols/AlertPresenting.swift | mit | 2 | //
// AlertPresenting.swift
// pass
//
// Copyright © 2022 Bob Sun. All rights reserved.
//
import UIKit
public typealias AlertAction = (UIAlertAction) -> Void
public protocol AlertPresenting {
func presentAlert(title: String, message: String)
func presentFailureAlert(title: String?, message: String, action: AlertAction?)
func presentAlertWithAction(title: String, message: String, action: AlertAction?)
}
public extension AlertPresenting where Self: UIViewController {
func presentAlert(title: String, message: String) {
presentAlert(
title: title,
message: message,
actions: [UIAlertAction(title: "OK", style: .cancel, handler: nil)]
)
}
// swiftlint:disable function_default_parameter_at_end
func presentFailureAlert(title: String? = nil, message: String, action: AlertAction? = nil) {
let title = title ?? "Error"
presentAlert(
title: title,
message: message,
actions: [UIAlertAction(title: "OK", style: .cancel, handler: action)]
)
}
func presentAlertWithAction(title: String, message: String, action: AlertAction?) {
presentAlert(
title: title,
message: message,
actions: [
UIAlertAction(title: "Yes", style: .default, handler: action),
UIAlertAction(title: "No", style: .cancel, handler: nil),
]
)
}
private func presentAlert(title: String, message: String, actions: [UIAlertAction] = []) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
actions.forEach { action in
alertController.addAction(action)
}
present(alertController, animated: true, completion: nil)
}
}
| a38142eef8b3a8e48916bf0a4d61c8e9 | 32.309091 | 103 | 0.629913 | false | false | false | false |
Tsukishita/CaveCommentViewer | refs/heads/master | CaveCommentViewer/CommentView.swift | mit | 1 | import UIKit
import Socket_IO_Client_Swift
import SwiftyJSON
import KeychainAccess
/*
Alert
N番のコメントのBANに失敗しました
管理者メッセージ
*/
class CommentView: UIViewController, UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,UIBarPositioningDelegate{
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var overlay: UIView!
//受け渡し用
var roomid: String?
var room_startTime:NSDate!
var room_name:String!
var room_author:String!
var IconImage:Dictionary<String,UIImage> = Dictionary()
var Socket: SocketIOClient!
var json:JSON?
var heights = [CGFloat]()
var live_status:Bool!
var timer :NSTimer?
let api = CaveAPI()
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var submitBtn: UIButton!
@IBOutlet weak var naviBar: UINavigationBar!
@IBOutlet weak var comLabel: UILabel!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var scrollview: UIScrollView!
@IBOutlet weak var userimg: UIImageView!
@IBOutlet weak var commimg: UIImageView!
@IBOutlet weak var ContentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.nameField.returnKeyType = .Done
self.naviBar.tintColor = UIColor.whiteColor()
self.naviBar.topItem?.title = room_name
self.submitBtn.layer.cornerRadius = 7
self.submitBtn.layer.borderWidth = 1
//後のカラー設定用
self.tableview.backgroundColor = UIColor(red: 1, green: 1, blue: 0.98, alpha: 1)
self.view.backgroundColor = UIColor(red:0.1,green:0.9,blue:0.4,alpha:0)
self.naviBar.barTintColor = UIColor(red:0.1,green:0.9,blue:0.4,alpha:1.0)
//self.submitBtn.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
self.submitBtn.layer.borderColor = UIColor.clearColor().CGColor
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
self.userimg.image = self.userimg.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
self.userimg.tintColor = .darkGrayColor()
self.commimg.image = self.commimg.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
self.commimg.tintColor = .darkGrayColor()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "rowButtonAction:")
longPressRecognizer.allowableMovement = 15
longPressRecognizer.minimumPressDuration = 0.6
self.tableview.addGestureRecognizer(longPressRecognizer)
//ログインしている場合はAPIKEYを取得しに行く
if self.api.accessKey == ""{
let alertController = UIAlertController(title: "アクセスキー取得失敗", message: "接続できませんでした", preferredStyle: .Alert)
let otherAction = UIAlertAction(title: "戻る", style: .Cancel) {action in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(otherAction)
dispatch_async(dispatch_get_main_queue()) {() in
self.presentViewController(alertController, animated: true, completion: nil)
}
}else if self.api.auth_user != ""{
self.api.getAPIKey({res in})
self.nameField.text = self.api.auth_user
}
Socket = SocketIOClient(
socketURL: "ws.cavelis.net",
options: ["connectParams":["accessKey":self.api.accessKey]])
Socket.on("ready") { data in
print("コメントサーバーに接続")
status.animation(str:"コメントサーバーに接続しました")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
Socket.on("connect") { data in
print("コメントサーバーに接続しました")
self.Socket.emit("get", [
"devkey":self.api.accessKey,
"roomId":self.roomid!])
}
Socket.on("get") {data, ack in
self.json = JSON(data)[0]["comments"]
self.labelHeight(res:{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if self.tableview != nil {
self.tableview.reloadData()
if self.json?.count != 0{
self.tableview.scrollToRowAtIndexPath(NSIndexPath(forRow: self.json!.count-1, inSection: 0),
atScrollPosition: UITableViewScrollPosition.Bottom, animated: false
)
}
let transition: CATransition = CATransition()
transition.duration = 0.4
transition.type = kCATransitionMoveIn
transition.subtype = kCATransitionFromBottom
self.comLabel.layer.addAnimation(transition, forKey: nil)
self.comLabel.text = "\(self.json!.count)"
}
})
})
if self.live_status! == true {
self.Socket.emit("join", [
"devkey":self.api.accessKey,
"roomId":self.roomid!])
self.timer = NSTimer.scheduledTimerWithTimeInterval(1/30, target: self, selector: "datemgr", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
}else{
self.overlay.hidden = false
self.timeLabel.text = "Archived"
}
}
Socket.on("post") {data, ack in
if self.json != nil{
let str = JSON(data)[0]["message"].stringValue
let url = JSON(data)[0]["user_icon"].string
if url != nil{
self.heights.append(floor(TableCellLayout(str: str, w: self.view.bounds.size.width).h)+4)
}else{
self.heights.append(floor(TableCellLayout(str: str, w: self.view.bounds.size.width).h)-8)
}
self.json = JSON(self.json!.arrayObject! + JSON(data).arrayObject!)
let transition: CATransition = CATransition()
transition.duration = 0.4
transition.type = kCATransitionMoveIn
transition.subtype = kCATransitionFromBottom
self.comLabel.layer.addAnimation(transition, forKey: nil)
self.comLabel.text = "\(self.json!.count)"
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableview.reloadData()
self.tableview.scrollToRowAtIndexPath(NSIndexPath(forRow: self.json!.count-1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
})
}
}
Socket.on("post_result"){data,ack in
if JSON(data)[0]["result"] == false{
let alertController = UIAlertController(title: "Network Error", message: "コメントの送信に失敗しました", preferredStyle: .Alert)
let otherAction = UIAlertAction(title: "閉じる", style: .Cancel) {action in
self.overlay.hidden = true
self.textField.enabled = false
}
alertController.addAction(otherAction)
self.presentViewController(alertController, animated: true, completion: nil)
}else{
status.animation(str:"投稿が完了しました")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.textField.text = ""
self.overlay.hidden = true
self.textField.enabled = true
}
}
Socket.on("join") {data, ack in
if JSON(data)[0]["ipcount"].stringValue != self.userLabel.text{
let transition: CATransition = CATransition()
transition.duration = 0.4
transition.type = kCATransitionMoveIn
transition.subtype = kCATransitionFromBottom
self.userLabel.layer.addAnimation(transition, forKey: nil)
}
self.userLabel.text = JSON(data)[0]["ipcount"].stringValue
}
Socket.on("leave") {data, ack in
if JSON(data)[0]["ipcount"].stringValue != self.userLabel.text{
let transition: CATransition = CATransition()
transition.duration = 0.4
transition.type = kCATransitionMoveIn
transition.subtype = kCATransitionFromTop
self.userLabel.layer.addAnimation(transition, forKey: nil)
}
self.userLabel.text = JSON(data)[0]["ipcount"].stringValue
}
Socket.on("close_entry") {data, ack in
let id = JSON(data)[0]["stream_name"].string
if self.roomid == id {
let alertController = UIAlertController(title: "放送が終了しました", message: "退室しますか?", preferredStyle: .Alert)
let otherAction = UIAlertAction(title: "はい", style: .Cancel) {action in
self.dismissViewControllerAnimated(true, completion: nil)
}
let cancelAction = UIAlertAction(title: "キャンセル", style: .Default) {action in
}
alertController.addAction(otherAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
Socket.on("ban_user") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番さんがBAN指定されました")
self.json![num-1] = json
self.tableview.reloadData()
}
Socket.on("unban_user") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番さんがBAN指定解除されました")
self.json![num-1] = json
self.tableview.reloadData()
}
Socket.on("ban_fail") {data, ack in
print("BAN指定失敗")
}
Socket.on("hide_comment") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番のコメントが非表示指定されました")
self.json![num-1] = json
self.tableview.reloadData()
}
Socket.on("show_comment") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番のコメントが再表示指定されました")
self.json![num-1] = json
self.tableview.reloadData()
}
Socket.on("show_id") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番さんのIDが表示指定されました")
}
Socket.on("hide_id") {data, ack in
let json = JSON(data)[0]
let num: Int = json["comment_num"].int!
status.animation(str: "\(num)番さんのIDが表示指定解除されました")
}
Socket.connect()
self.scrollview.contentInset=UIEdgeInsetsMake(0,0,0,0);
}
func labelHeight(res res:()-> Void){
if self.json?.count != 0{
let count = self.json!.count
for row in 0...count-1 {
let str = self.json![row]["message"].stringValue
let url = self.json![row]["user_icon"].string
if url != nil{
heights.append(floor(TableCellLayout(str: str, w: self.view.bounds.size.width).h)+4)
}else{
heights.append(floor(TableCellLayout(str: str, w: self.view.bounds.size.width).h)-8)
}
}
}
res()
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return UIBarPosition.TopAttached
}
func keyboardWillShow(notification: NSNotification){
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let myBoundSize: CGSize = UIScreen.mainScreen().bounds.size
let txtLimit = ContentView.frame.origin.y + textField.frame.height + 144
let kbdLimit = myBoundSize.height - keyboardScreenEndFrame.size.height
if txtLimit >= kbdLimit {
scrollview.contentOffset.y = txtLimit - kbdLimit
}
}
func keyboardWillHide(notification: NSNotification){
self.scrollview.contentOffset.y = 0
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.view.removeFromSuperview()
NSNotificationCenter.defaultCenter().removeObserver(self)
json = nil
IconImage.removeAll()
timer = nil
}
func datemgr() {
let date2 = NSDate()
let time = Int(date2.timeIntervalSinceDate(room_startTime!))
self.timeLabel.text = datetoStr(time)
}
func datetoStr(time:Int) -> String{
let hour:Int = time / 3600
let min:Int = (time-hour*3600)/60
let sec:Int = time-hour*3600 - min*60
let minS:String = min > 9 ? "\(min)" : "0\(min)"
let secS:String = sec > 9 ? "\(sec)" : "0\(sec)"
let attime:String = "\(hour):\(minS):\(secS)"
return attime
}
override func didReceiveMemoryWarning() {}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// 行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.json != nil {
return self.json!.count
}else{
return 0
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return heights[indexPath.row]
}
// セルの設定
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CommentCell = tableView.dequeueReusableCellWithIdentifier("CommentCell", forIndexPath: indexPath) as! CommentCell
let comment = json![indexPath.row]
cell.labelName.preferredMaxLayoutWidth = CGFloat(100)
let imgURL = "http:\(comment["user_icon"].stringValue)"
let unixInt:Double = comment["time"].doubleValue/1000
let date = NSDate(timeIntervalSince1970: unixInt)
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "ja")
formatter.dateFormat = "MM/dd HH:mm:ss"
let time = Int(date.timeIntervalSinceDate(room_startTime!))
cell.labelTime.text = "\(formatter.stringFromDate(date)) (\(datetoStr(time)))"
cell.labelNum.text = comment["comment_num"].stringValue
cell.labelName.text = comment["name"].stringValue
cell.labelComment.text = comment["message"].stringValue
if IconImage[comment["name"].stringValue] == nil{
if imgURL != "http:"{
let url = NSURL(string:imgURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
let request = NSMutableURLRequest(URL: url!)
let task : NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue()) { () in
self.IconImage[comment["name"].stringValue] = UIImage(data:data!)
cell.imgUser.image = UIImage(data:data!)
}
}
}
task.resume()
}else{
cell.imgUser.image = nil
}
}else{
cell.imgUser.image = IconImage[comment["name"].stringValue]
}
cell.imgUser.layer.shadowOpacity = 0.1
cell.imgUser.layer.shadowOffset = CGSizeMake(0, 0);
let id = comment["user_id"].stringValue
if id != ""{
cell.labelID.text = "ID:\(comment["user_id"].stringValue)"
}else{
cell.labelID.text = ""
}
cell.layoutIfNeeded()
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:(NSIndexPath)) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func rowButtonAction(sender : UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
if self.api.auth_user != room_author{
return
}
let indexPath = tableview.indexPathForRowAtPoint(sender.locationInView(tableview))
if indexPath == nil {
return
}
let comment = json![indexPath!.row]
let ban_str = comment["is_ban"] ? "BAN指定解除" : "BAN指定"
let hiddenCom_str = comment["is_hide"] ? "コメント再表示" : "コメント非表示"
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let ban_user = UIAlertAction(title: ban_str, style: .Default) {
action in
self.Socket.emit((comment["is_ban"] ? "unban" : "ban"), [
"devkey":self.api.devKey,
"apikey":self.api.apiKey,
"roomId":self.roomid!,
"commentNumber":indexPath!.row+1])
}
let unhiddenID = UIAlertAction(title: "ID表示", style: .Default) {
action in
self.Socket.emit("show_id", [
"devkey":self.api.devKey,
"apikey":self.api.apiKey,
"roomId":self.roomid!,
"commentNumber":indexPath!.row+1])
}
let hiddenID = UIAlertAction(title: "ID非表示", style: .Default) {
action in
self.Socket.emit("hide_id", [
"devkey":self.api.devKey,
"apikey":self.api.apiKey,
"roomId":self.roomid!,
"commentNumber":indexPath!.row+1])
}
let hiddenCom = UIAlertAction(title: hiddenCom_str, style: .Default) {
action in
self.Socket.emit((comment["is_hide"] ? "show_comment" : "hide_comment"), [
"devkey":self.api.devKey,
"apikey":self.api.apiKey,
"roomId":self.roomid!,
"commentNumber":indexPath!.row+1])
}
let Cancel = UIAlertAction(title: "キャンセル", style: .Cancel) {
action in
}
alertController.addAction(ban_user)
alertController.addAction(hiddenID)
alertController.addAction(unhiddenID)
alertController.addAction(hiddenCom)
alertController.addAction(Cancel)
presentViewController(alertController, animated: true, completion: nil)
}
}
@IBAction func Connect(sender: AnyObject) {
if textField.text != ""{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.textField.enabled = false
var str:[String:String] = [
"devkey":self.api.devKey,
"roomId":self.roomid!,
"message":self.textField.text!,
"name":self.nameField.text!,
"apikey":self.api.apiKey
]
if self.api.apiKey != "" && self.nameField.text == self.api.auth_user{
str["apikey"] = self.api.apiKey
}
self.view.bringSubviewToFront(overlay)
self.overlay.hidden = false
self.Socket.emit("post", str)
}
}
@IBAction func closeModal(sender: UIBarButtonItem) {
self.Socket.emit("leave", [
"devkey":self.api.devKey,
"roomId":self.roomid!])
self.Socket.disconnect()
self.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
class TableCellLayout{
var txt: String?
var cellWidth: CGFloat = 0
var _h: CGFloat = 0
let PaddingTop: CGFloat = 12
let PaddingBottom: CGFloat = 40
let PaddingLeft: CGFloat = 10
let PaddingRight: CGFloat = 10
let LabelMinHeight: CGFloat = 16
var h: CGFloat{
set{_h = newValue}
get{
let sum = max(stringSize().height, LabelMinHeight)
let lineHeight = CGFloat(Int(sum / LabelMinHeight)) * 0.7
return CGFloat(Int(sum + lineHeight + PaddingTop + PaddingBottom ))
}
}
init(str: String, w: CGFloat){
txt = str
cellWidth = w
}
func stringSize() -> CGSize {
//cellの幅から余白を引いたLabelの幅
let maxSize = CGSizeMake(cellWidth - PaddingLeft - PaddingRight, CGFloat.max)
let attr = [NSFontAttributeName:UIFont.systemFontOfSize(14)]
let nsStr: NSString = NSString(string: txt!)
//フォントとLabel幅からサイズを取得
let strSize: CGRect = nsStr.boundingRectWithSize(maxSize, options: .UsesLineFragmentOrigin, attributes: attr, context: nil)
return strSize.size
}
} | 384a8a89e0cea3584421c5a34dfb11c9 | 40.081818 | 180 | 0.552305 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Vender/Box/BoxType.swift | mit | 1 | // Copyright (c) 2014 Rob Rix. All rights reserved.
// MARK: BoxType
/// The type conformed to by all boxes.
public protocol BoxType {
/// The type of the wrapped value.
associatedtype Value
/// Initializes an intance of the type with a value.
init(_ value: Value)
/// The wrapped value.
var value: Value { get }
}
/// The type conformed to by mutable boxes.
public protocol MutableBoxType: BoxType {
/// The (mutable) wrapped value.
var value: Value { get set }
}
// MARK: Equality
/// Equality of `BoxType`s of `Equatable` types.
///
/// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition.
public func == <B: BoxType> (lhs: B, rhs: B) -> Bool where B.Value: Equatable {
return lhs.value == rhs.value
}
/// Inequality of `BoxType`s of `Equatable` types.
///
/// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition.
public func != <B: BoxType> (lhs: B, rhs: B) -> Bool where B.Value: Equatable {
return lhs.value != rhs.value
}
// MARK: Map
/// Maps the value of a box into a new box.
public func map<B: BoxType, C: BoxType>(v: B, f: (B.Value) -> C.Value) -> C {
return C(f(v.value))
}
| 018eafa03f685d5b0ffdc11a72f1a0f9 | 25.913043 | 119 | 0.668013 | false | false | false | false |
chrisamanse/SWXMLHash | refs/heads/master | Source/SWXMLHash.swift | mit | 2 | //
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
let rootElementName = "SWXMLHash_Root_Element"
/// Parser options
public class SWXMLHashOptions {
internal init() {}
/// determines whether to parse the XML with lazy parsing or not
public var shouldProcessLazily = false
/// determines whether to parse XML namespaces or not (forwards to `NSXMLParser.shouldProcessNamespaces`)
public var shouldProcessNamespaces = false
}
/// Simple XML parser
public class SWXMLHash {
let options: SWXMLHashOptions
private init(_ options: SWXMLHashOptions = SWXMLHashOptions()) {
self.options = options
}
class public func config(configAction: (SWXMLHashOptions) -> ()) -> SWXMLHash {
let opts = SWXMLHashOptions()
configAction(opts)
return SWXMLHash(opts)
}
public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
public func parse(data: NSData) -> XMLIndexer {
let parser: SimpleXmlParser = options.shouldProcessLazily ? LazyXMLParser(options) : XMLParser(options)
return parser.parse(data)
}
/**
Method to parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return SWXMLHash().parse(xml)
}
/**
Method to parse XML passed in as an NSData instance.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
return SWXMLHash().parse(data)
}
/**
Method to lazily parse XML passed in as a string.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(xml: String) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(xml)
}
/**
Method to lazily parse XML passed in as an NSData instance.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(data: NSData) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
protocol SimpleXmlParser {
init(_ options: SWXMLHashOptions)
func parse(data: NSData) -> XMLIndexer
}
/// The implementation of NSXMLParserDelegate and where the lazy parsing actually happens.
class LazyXMLParser: NSObject, SimpleXmlParser, NSXMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
let options: SWXMLHashOptions
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if !onMatch() {
return
}
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return elementStack.items.startsWith(ops.map { $0.key })
}
else {
return ops.map { $0.key }.startsWith(elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser: NSObject, SimpleXmlParser, NSXMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
let options: SWXMLHashOptions
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
parentStack.pop()
}
}
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer: SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case XMLError(Error)
public enum Error: ErrorType {
case Attribute(attr: String)
case AttributeValue(attr: String, value: String)
case Key(key: String)
case Index(idx: Int)
case Init(instance: AnyObject)
case Error
}
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }) {
for elem in elem.children {
list.append(XMLIndexer(elem))
}
}
return list
}
/**
Allows for element lookup by matching attribute values.
- parameter attr: should the name of the attribute to match on
- parameter value: should be the value of the attribute to match on
- returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return try match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({$0.attributes[attr] == value}).first {
return .Element(elem)
}
throw Error.AttributeValue(attr: attr, value: value)
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
throw Error.AttributeValue(attr: attr, value: value)
}
fallthrough
default:
throw Error.Attribute(attr: attr)
}
}
/**
Initializes the XMLIndexer
- parameter _: should be an instance of XMLElement, but supports other values for error handling
- returns: instance of XMLIndexer
*/
public init(_ rawObject: AnyObject) throws {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
throw Error.Init(instance: rawObject)
}
}
public init(_ el: XMLElement) {
self = .Element(el)
}
init(_ stream: LazyXMLParser) {
self = .Stream(IndexOps(parser: stream))
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
- errors: throws a XMLIndexerError.Key if no element was found
*/
// Because Swift 2 does not support throwing subscripts use the byKey and byIndex function instead
// TODO: Change to throwing subscripts if avaiable in futher releases
public func byKey(key: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.children.filter({ $0.name == key })
if match.count > 0 {
if match.count == 1 {
return .Element(match[0])
}
else {
return .List(match)
}
}
fallthrough
default:
throw Error.Key(key: key)
}
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by
*/
public subscript(key: String) -> XMLIndexer {
do {
return try self.byKey(key)
} catch let error as Error {
return .XMLError(error)
} catch {
return .XMLError(.Key(key: key))
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
- parameter index: The 0-based index to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
*/
// TODO: Change to throwing subscripts if avaiable in futher releases
public func byIndex(index: Int) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .XMLError(.Index(idx: index))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
fallthrough
default:
return .XMLError(.Index(idx: index))
}
}
public subscript(index: Int) -> XMLIndexer {
do {
return try byIndex(index)
} catch let error as Error {
return .XMLError(error)
} catch {
return .XMLError(.Index(idx: index))
}
}
typealias GeneratorType = XMLIndexer
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
switch self {
case .XMLError:
return false
default:
return true
}
}
}
extension XMLIndexer: CustomStringConvertible {
public var description: String {
switch self {
case .List(let list):
return list.map { $0.description }.joinWithSeparator("\n")
case .Element(let elem):
if elem.name == rootElementName {
return elem.children.map { $0.description }.joinWithSeparator("\n")
}
return elem.description
default:
return ""
}
}
}
extension XMLIndexer.Error: CustomStringConvertible {
public var description: String {
switch self {
case .Attribute(let attr):
return "XML Attribute Error: Missing attribute [\"\(attr)\"]"
case .AttributeValue(let attr, let value):
return "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"
case .Key(let key):
return "XML Element Error: Incorrect key [\"\(key)\"]"
case .Index(let index):
return "XML Element Error: Incorrect index [\"\(index)\"]"
case .Init(let instance):
return "XML Indexer Error: initialization with Object [\"\(instance)\"]"
case .Error:
return "Unknown Error"
}
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement {
/// The name of the element
public let name: String
/// The inner text of the element, if it exists
public var text: String?
/// The attributes of the element
public var attributes = [String:String]()
var children = [XMLElement]()
var count: Int = 0
var index: Int
/**
Initialize an XMLElement instance
- parameter name: The name of the element to be initialized
- returns: a new instance of XMLElement
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameter name: The name of the new element to be added
- parameter withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count++
children.append(element)
for (keyAny,valueAny) in attributes {
if let key = keyAny as? String,
let value = valueAny as? String {
element.attributes[key] = value
}
}
return element
}
}
extension XMLElement: CustomStringConvertible {
public var description: String {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = attributesStringList.joinWithSeparator(" ")
if !attributesString.isEmpty {
attributesString = " " + attributesString
}
if children.count > 0 {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joinWithSeparator("\n")
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
}
else {
return "<\(name)\(attributesString)/>"
}
}
}
| bca61a4452a9522faccef642942d453e | 28.565284 | 172 | 0.603263 | false | false | false | false |
danielsaidi/iExtra | refs/heads/master | iExtra/UI/Extensions/UIImage/UIImage+Combine.swift | mit | 1 | //
// UIImage+Combine.swift
// iExtra
//
// Created by Daniel Saidi on 2015-11-19.
// Copyright © 2015 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIImage {
func combined(with image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let bottomRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
draw(in: bottomRect)
let topSize = image.size
let topSizeHeightDiff = size.height - topSize.height
let topSizeWidthDiff = size.width - topSize.width
let topRect = bottomRect.insetBy(dx: topSizeHeightDiff / 2, dy: topSizeWidthDiff / 2)
image.draw(in: topRect, blendMode: .normal, alpha: 1)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result ?? UIImage()
}
}
| a8493929306e52f53e6bdb780c3d9f8f | 30.137931 | 93 | 0.648948 | false | false | false | false |
sishenyihuba/Weibo | refs/heads/master | Weibo/00-Main(主要)/OAuth/UserAccountViewModel.swift | mit | 1 | //
// UserAccountViewModel.swift
// Weibo
//
// Created by daixianglong on 2017/1/16.
// Copyright © 2017年 Dale. All rights reserved.
//
import UIKit
class UserAccountViewModel {
static var sharedInstance :UserAccountViewModel = UserAccountViewModel()
//MARK: - 计算属性
var accountPath:String {
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
return (path as NSString).stringByAppendingPathComponent("account.plist")
}
var isLogin:Bool {
if let account = account {
if let expires_date = account.expires_date {
return expires_date.compare(NSDate()) == .OrderedDescending
}
}
return false
}
//MARK: - 存储属性
var account:UserAccount?
init() {
account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
}
}
| fc351c0d2f51b3518986f590ba4bbf66 | 23.307692 | 104 | 0.627637 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Reader/Tab Navigation/ReaderTabView.swift | gpl-2.0 | 1 | import UIKit
class ReaderTabView: UIView {
private let mainStackView: UIStackView
private let buttonsStackView: UIStackView
private let tabBar: FilterTabBar
private let filterButton: PostMetaButton
private let resetFilterButton: UIButton
private let horizontalDivider: UIView
private let containerView: UIView
private var loadingView: UIView?
private let viewModel: ReaderTabViewModel
private var filteredTabs: [(index: Int, topic: ReaderAbstractTopic)] = []
private var previouslySelectedIndex: Int = 0
private var discoverIndex: Int? {
return tabBar.items.firstIndex(where: { ($0 as? ReaderTabItem)?.content.topicType == .discover })
}
private var p2Index: Int? {
return tabBar.items.firstIndex(where: { (($0 as? ReaderTabItem)?.content.topic as? ReaderTeamTopic)?.organizationID == SiteOrganizationType.p2.rawValue })
}
init(viewModel: ReaderTabViewModel) {
mainStackView = UIStackView()
buttonsStackView = UIStackView()
tabBar = FilterTabBar()
filterButton = PostMetaButton(type: .custom)
resetFilterButton = UIButton(type: .custom)
horizontalDivider = UIView()
containerView = UIView()
self.viewModel = viewModel
super.init(frame: .zero)
viewModel.didSelectIndex = { [weak self] index in
self?.tabBar.setSelectedIndex(index)
self?.toggleButtonsView()
}
viewModel.onTabBarItemsDidChange { [weak self] tabItems, index in
self?.tabBar.items = tabItems
self?.tabBar.setSelectedIndex(index)
self?.configureTabBarElements()
self?.hideGhost()
self?.addContentToContainerView()
}
setupViewElements()
NotificationCenter.default.addObserver(self, selector: #selector(topicUnfollowed(_:)), name: .ReaderTopicUnfollowed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(siteFollowed(_:)), name: .ReaderSiteFollowed, object: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI setup
extension ReaderTabView {
/// Call this method to set the title of the filter button
private func setFilterButtonTitle(_ title: String) {
WPStyleGuide.applyReaderFilterButtonTitle(filterButton, title: title)
}
private func setupViewElements() {
backgroundColor = .filterBarBackground
setupMainStackView()
setupTabBar()
setupButtonsView()
setupFilterButton()
setupResetFilterButton()
setupHorizontalDivider(horizontalDivider)
activateConstraints()
}
private func setupMainStackView() {
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.axis = .vertical
addSubview(mainStackView)
mainStackView.addArrangedSubview(tabBar)
mainStackView.addArrangedSubview(buttonsStackView)
mainStackView.addArrangedSubview(horizontalDivider)
mainStackView.addArrangedSubview(containerView)
}
private func setupTabBar() {
tabBar.tabBarHeight = Appearance.barHeight
WPStyleGuide.configureFilterTabBar(tabBar)
tabBar.addTarget(self, action: #selector(selectedTabDidChange(_:)), for: .valueChanged)
viewModel.fetchReaderMenu()
}
private func configureTabBarElements() {
guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else {
return
}
previouslySelectedIndex = tabBar.selectedIndex
buttonsStackView.isHidden = tabItem.shouldHideButtonsView
horizontalDivider.isHidden = tabItem.shouldHideButtonsView
}
private func setupButtonsView() {
buttonsStackView.translatesAutoresizingMaskIntoConstraints = false
buttonsStackView.isLayoutMarginsRelativeArrangement = true
buttonsStackView.axis = .horizontal
buttonsStackView.alignment = .fill
buttonsStackView.addArrangedSubview(filterButton)
buttonsStackView.addArrangedSubview(resetFilterButton)
buttonsStackView.isHidden = true
}
private func setupFilterButton() {
filterButton.translatesAutoresizingMaskIntoConstraints = false
filterButton.contentEdgeInsets = Appearance.filterButtonInsets
filterButton.imageEdgeInsets = Appearance.filterButtonimageInsets
filterButton.titleEdgeInsets = Appearance.filterButtonTitleInsets
filterButton.contentHorizontalAlignment = .leading
filterButton.titleLabel?.font = Appearance.filterButtonFont
WPStyleGuide.applyReaderFilterButtonStyle(filterButton)
setFilterButtonTitle(Appearance.defaultFilterButtonTitle)
filterButton.addTarget(self, action: #selector(didTapFilterButton), for: .touchUpInside)
filterButton.accessibilityIdentifier = Accessibility.filterButtonIdentifier
}
private func setupResetFilterButton() {
resetFilterButton.translatesAutoresizingMaskIntoConstraints = false
resetFilterButton.contentEdgeInsets = Appearance.resetButtonInsets
WPStyleGuide.applyReaderResetFilterButtonStyle(resetFilterButton)
resetFilterButton.addTarget(self, action: #selector(didTapResetFilterButton), for: .touchUpInside)
resetFilterButton.isHidden = true
resetFilterButton.accessibilityIdentifier = Accessibility.resetButtonIdentifier
resetFilterButton.accessibilityLabel = Accessibility.resetFilterButtonLabel
}
private func setupHorizontalDivider(_ divider: UIView) {
divider.translatesAutoresizingMaskIntoConstraints = false
divider.backgroundColor = Appearance.dividerColor
}
private func addContentToContainerView() {
guard let controller = self.next as? UIViewController,
let childController = viewModel.makeChildContentViewController(at: tabBar.selectedIndex) else {
return
}
containerView.translatesAutoresizingMaskIntoConstraints = false
childController.view.translatesAutoresizingMaskIntoConstraints = false
controller.children.forEach {
$0.remove()
}
controller.add(childController)
containerView.pinSubviewToAllEdges(childController.view)
if viewModel.shouldShowCommentSpotlight {
let title = NSLocalizedString("Comment to start making connections.", comment: "Hint for users to grow their audience by commenting on other blogs.")
childController.displayNotice(title: title)
}
}
private func activateConstraints() {
pinSubviewToAllEdges(mainStackView)
NSLayoutConstraint.activate([
buttonsStackView.heightAnchor.constraint(equalToConstant: Appearance.barHeight),
resetFilterButton.widthAnchor.constraint(equalToConstant: Appearance.resetButtonWidth),
horizontalDivider.heightAnchor.constraint(equalToConstant: Appearance.dividerWidth),
horizontalDivider.widthAnchor.constraint(equalTo: mainStackView.widthAnchor)
])
}
func applyFilter(for selectedTopic: ReaderAbstractTopic?) {
guard let selectedTopic = selectedTopic else {
return
}
let selectedIndex = self.tabBar.selectedIndex
// Remove any filters for selected index, then add new filter to array.
self.filteredTabs.removeAll(where: { $0.index == selectedIndex })
self.filteredTabs.append((index: selectedIndex, topic: selectedTopic))
self.resetFilterButton.isHidden = false
self.setFilterButtonTitle(selectedTopic.title)
}
}
// MARK: - Actions
private extension ReaderTabView {
/// Tab bar
@objc func selectedTabDidChange(_ tabBar: FilterTabBar) {
// If the tab was previously filtered, refilter it.
// Otherwise reset the filter.
if let existingFilter = filteredTabs.first(where: { $0.index == tabBar.selectedIndex }) {
if previouslySelectedIndex == discoverIndex {
// Reset the container view to show a feed's content.
addContentToContainerView()
}
viewModel.setFilterContent(topic: existingFilter.topic)
resetFilterButton.isHidden = false
setFilterButtonTitle(existingFilter.topic.title)
} else {
addContentToContainerView()
}
previouslySelectedIndex = tabBar.selectedIndex
viewModel.showTab(at: tabBar.selectedIndex)
toggleButtonsView()
}
func toggleButtonsView() {
guard let tabItems = tabBar.items as? [ReaderTabItem] else {
return
}
// hide/show buttons depending on the selected tab. Do not execute the animation if not necessary.
guard buttonsStackView.isHidden != tabItems[tabBar.selectedIndex].shouldHideButtonsView else {
return
}
let shouldHideButtons = tabItems[self.tabBar.selectedIndex].shouldHideButtonsView
self.buttonsStackView.isHidden = shouldHideButtons
self.horizontalDivider.isHidden = shouldHideButtons
}
/// Filter button
@objc func didTapFilterButton() {
/// Present from the image view to align to the left hand side
viewModel.presentFilter(from: filterButton.imageView ?? filterButton) { [weak self] selectedTopic in
guard let self = self else {
return
}
self.applyFilter(for: selectedTopic)
}
}
/// Reset filter button
@objc func didTapResetFilterButton() {
filteredTabs.removeAll(where: { $0.index == tabBar.selectedIndex })
setFilterButtonTitle(Appearance.defaultFilterButtonTitle)
resetFilterButton.isHidden = true
guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else {
return
}
viewModel.resetFilter(selectedItem: tabItem)
}
@objc func topicUnfollowed(_ notification: Foundation.Notification) {
guard let userInfo = notification.userInfo,
let topic = userInfo[ReaderNotificationKeys.topic] as? ReaderAbstractTopic,
let existingFilter = filteredTabs.first(where: { $0.topic == topic }) else {
return
}
filteredTabs.removeAll(where: { $0 == existingFilter })
if existingFilter.index == tabBar.selectedIndex {
didTapResetFilterButton()
}
}
@objc func siteFollowed(_ notification: Foundation.Notification) {
guard let userInfo = notification.userInfo,
let site = userInfo[ReaderNotificationKeys.topic] as? ReaderSiteTopic,
site.organizationType == .p2,
p2Index == nil else {
return
}
// If a P2 is followed but the P2 tab is not in the Reader tab bar,
// refresh the Reader menu to display it.
viewModel.fetchReaderMenu()
}
}
// MARK: - Ghost
private extension ReaderTabView {
/// Build the ghost tab bar
func makeGhostTabBar() -> FilterTabBar {
let ghostTabBar = FilterTabBar()
ghostTabBar.items = Appearance.ghostTabItems
ghostTabBar.isUserInteractionEnabled = false
ghostTabBar.tabBarHeight = Appearance.barHeight
ghostTabBar.dividerColor = .clear
return ghostTabBar
}
/// Show the ghost tab bar
func showGhost() {
let ghostTabBar = makeGhostTabBar()
tabBar.addSubview(ghostTabBar)
tabBar.pinSubviewToAllEdges(ghostTabBar)
loadingView = ghostTabBar
ghostTabBar.startGhostAnimation(style: GhostStyle(beatDuration: GhostStyle.Defaults.beatDuration,
beatStartColor: .placeholderElement,
beatEndColor: .placeholderElementFaded))
}
/// Hide the ghost tab bar
func hideGhost() {
loadingView?.stopGhostAnimation()
loadingView?.removeFromSuperview()
loadingView = nil
}
struct GhostTabItem: FilterTabBarItem {
var title: String
let accessibilityIdentifier = ""
}
}
// MARK: - Appearance
private extension ReaderTabView {
enum Appearance {
static let barHeight: CGFloat = 48
static let tabBarAnimationsDuration = 0.2
static let defaultFilterButtonTitle = NSLocalizedString("Filter", comment: "Title of the filter button in the Reader")
static let filterButtonMaxFontSize: CGFloat = 28.0
static let filterButtonFont = WPStyleGuide.fontForTextStyle(.headline, fontWeight: .regular)
static let filterButtonInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
static let filterButtonimageInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
static let filterButtonTitleInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
static let resetButtonWidth: CGFloat = 32
static let resetButtonInsets = UIEdgeInsets(top: 1, left: -4, bottom: -1, right: 4)
static let dividerWidth: CGFloat = .hairlineBorderWidth
static let dividerColor: UIColor = .divider
// "ghost" titles are set to the default english titles, as they won't be visible anyway
static let ghostTabItems = [GhostTabItem(title: "Following"), GhostTabItem(title: "Discover"), GhostTabItem(title: "Likes"), GhostTabItem(title: "Saved")]
}
}
// MARK: - Accessibility
extension ReaderTabView {
private enum Accessibility {
static let filterButtonIdentifier = "ReaderFilterButton"
static let resetButtonIdentifier = "ReaderResetButton"
static let resetFilterButtonLabel = NSLocalizedString("Reset filter", comment: "Accessibility label for the reset filter button in the reader.")
}
}
| 93b7f916d92b132ad25e3a3783e36fd0 | 36.281501 | 162 | 0.685388 | false | false | false | false |
RevenueCat/purchases-ios | refs/heads/main | Sources/Purchasing/StoreKit1/ProductsFetcherSK1.swift | mit | 1 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ProductsFetcherSK1.swift
//
// Created by Andrés Boedo on 7/26/21.
import Foundation
import StoreKit
final class ProductsFetcherSK1: NSObject {
typealias Callback = (Result<Set<SK1Product>, PurchasesError>) -> Void
let requestTimeout: TimeInterval
private let productsRequestFactory: ProductsRequestFactory
// Note: these 3 must be used only inside `queue` to be thread-safe.
private var cachedProductsByIdentifier: [String: SK1Product] = [:]
private var productsByRequests: [SKRequest: ProductRequest] = [:]
private var completionHandlers: [Set<String>: [Callback]] = [:]
private let queue = DispatchQueue(label: "ProductsFetcherSK1")
private static let numberOfRetries: Int = 10
/// - Parameter requestTimeout: requests made by this class will return after whichever condition comes first:
/// - A success
/// - Retries up to ``Self.numberOfRetries``
/// - Timeout specified by this parameter
init(productsRequestFactory: ProductsRequestFactory = ProductsRequestFactory(),
requestTimeout: TimeInterval) {
self.productsRequestFactory = productsRequestFactory
self.requestTimeout = requestTimeout
}
func sk1Products(withIdentifiers identifiers: Set<String>,
completion: @escaping Callback) {
guard identifiers.count > 0 else {
completion(.success([]))
return
}
self.queue.async { [self] in
let productsAlreadyCached = self.cachedProductsByIdentifier.filter { key, _ in identifiers.contains(key) }
if productsAlreadyCached.count == identifiers.count {
let productsAlreadyCachedSet = Set(productsAlreadyCached.values)
Logger.debug(Strings.offering.products_already_cached(identifiers: identifiers))
completion(.success(productsAlreadyCachedSet))
return
}
if let existingHandlers = self.completionHandlers[identifiers] {
Logger.debug(Strings.offering.found_existing_product_request(identifiers: identifiers))
self.completionHandlers[identifiers] = existingHandlers + [completion]
return
}
Logger.debug(
Strings.storeKit.no_cached_products_starting_store_products_request(identifiers: identifiers)
)
self.completionHandlers[identifiers] = [completion]
let request = self.startRequest(forIdentifiers: identifiers, retriesLeft: Self.numberOfRetries)
self.scheduleCancellationInCaseOfTimeout(for: request)
}
}
// Note: this isn't thread-safe and must therefore be used inside of `queue` only.
@discardableResult
private func startRequest(forIdentifiers identifiers: Set<String>, retriesLeft: Int) -> SKProductsRequest {
let request = self.productsRequestFactory.request(productIdentifiers: identifiers)
request.delegate = self
self.productsByRequests[request] = .init(identifiers, retriesLeft: retriesLeft)
request.start()
return request
}
func products(withIdentifiers identifiers: Set<String>,
completion: @escaping (Result<Set<SK1StoreProduct>, PurchasesError>) -> Void) {
TimingUtil.measureAndLogIfTooSlow(
threshold: .productRequest,
message: Strings.storeKit.sk1_product_request_too_slow,
work: { completion in
self.sk1Products(withIdentifiers: identifiers) { skProducts in
completion(skProducts.map { Set($0.map(SK1StoreProduct.init)) })
}
},
result: completion
)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *)
func products(withIdentifiers identifiers: Set<String>) async throws -> Set<SK1StoreProduct> {
return try await Async.call { completion in
self.products(withIdentifiers: identifiers, completion: completion)
}
}
}
private extension ProductsFetcherSK1 {
struct ProductRequest {
let identifiers: Set<String>
var retriesLeft: Int
init(_ identifiers: Set<String>, retriesLeft: Int) {
self.identifiers = identifiers
self.retriesLeft = retriesLeft
}
}
}
extension ProductsFetcherSK1: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
self.queue.async { [self] in
Logger.rcSuccess(Strings.storeKit.store_product_request_received_response)
guard let productRequest = self.productsByRequests[request] else {
Logger.error("requested products not found for request: \(request)")
return
}
guard let completionBlocks = self.completionHandlers[productRequest.identifiers] else {
Logger.error("callback not found for failing request: \(request)")
self.productsByRequests.removeValue(forKey: request)
return
}
self.completionHandlers.removeValue(forKey: productRequest.identifiers)
self.productsByRequests.removeValue(forKey: request)
self.cacheProducts(response.products)
for completion in completionBlocks {
completion(.success(Set(response.products)))
}
}
}
func requestDidFinish(_ request: SKRequest) {
Logger.rcSuccess(Strings.storeKit.store_product_request_finished)
self.cancelRequestToPreventTimeoutWarnings(request)
}
func request(_ request: SKRequest, didFailWithError error: Error) {
defer {
self.cancelRequestToPreventTimeoutWarnings(request)
}
self.queue.async { [self] in
Logger.appleError(Strings.storeKit.store_products_request_failed(error: error))
guard let productRequest = self.productsByRequests[request] else {
Logger.error(Strings.purchase.requested_products_not_found(request: request))
return
}
if productRequest.retriesLeft <= 0 {
guard let completionBlocks = self.completionHandlers[productRequest.identifiers] else {
Logger.error(Strings.purchase.callback_not_found_for_request(request: request))
self.productsByRequests.removeValue(forKey: request)
return
}
self.completionHandlers.removeValue(forKey: productRequest.identifiers)
self.productsByRequests.removeValue(forKey: request)
for completion in completionBlocks {
completion(.failure(ErrorUtils.purchasesError(withSKError: error)))
}
} else {
let delayInSeconds = Int((self.requestTimeout / 10).rounded())
self.queue.asyncAfter(deadline: .now() + .seconds(delayInSeconds)) { [self] in
self.startRequest(forIdentifiers: productRequest.identifiers,
retriesLeft: productRequest.retriesLeft - 1)
}
}
}
}
func cacheProduct(_ product: SK1Product) {
self.queue.async {
self.cachedProductsByIdentifier[product.productIdentifier] = product
}
}
/// - Returns (via callback): The product identifiers that were removed, or empty if there were not
/// cached products.
func clearCache(completion: ((Set<String>) -> Void)? = nil) {
self.queue.async {
let cachedProductIdentifiers = self.cachedProductsByIdentifier.keys
if !cachedProductIdentifiers.isEmpty {
Logger.debug(Strings.offering.product_cache_invalid_for_storefront_change)
self.cachedProductsByIdentifier.removeAll(keepingCapacity: false)
}
completion?(Set(cachedProductIdentifiers))
}
}
}
private extension ProductsFetcherSK1 {
func cacheProducts(_ products: [SK1Product]) {
self.queue.async {
let productsByIdentifier = products.dictionaryAllowingDuplicateKeys {
$0.productIdentifier
}
self.cachedProductsByIdentifier += productsByIdentifier
}
}
// Even though the request has finished, we've seen instances where
// the request seems to live on. So we manually call `cancel` to prevent warnings in runtime.
// https://github.com/RevenueCat/purchases-ios/issues/250
// https://github.com/RevenueCat/purchases-ios/issues/391
func cancelRequestToPreventTimeoutWarnings(_ request: SKRequest) {
request.cancel()
}
// Even though there's a specific delegate method for when SKProductsRequest fails,
// there seem to be some situations in which SKProductsRequest hangs forever,
// without timing out and calling the delegate.
// So we schedule a cancellation just in case, and skip it if all goes as expected.
// More information: https://rev.cat/skproductsrequest-hangs
func scheduleCancellationInCaseOfTimeout(for request: SKProductsRequest) {
self.queue.asyncAfter(deadline: .now() + self.requestTimeout) { [weak self] in
guard let self = self,
let productRequest = self.productsByRequests[request] else { return }
request.cancel()
Logger.appleError(Strings.storeKit.skproductsrequest_timed_out(
after: Int(self.requestTimeout.rounded())
))
guard let completionBlocks = self.completionHandlers[productRequest.identifiers] else {
Logger.error("callback not found for failing request: \(request)")
return
}
self.completionHandlers.removeValue(forKey: productRequest.identifiers)
self.productsByRequests.removeValue(forKey: request)
for completion in completionBlocks {
completion(.failure(ErrorUtils.productRequestTimedOutError()))
}
}
}
}
// @unchecked because:
// - It has mutable state, but it's made thread-safe through `queue`.
extension ProductsFetcherSK1: @unchecked Sendable {}
| a6dc7ede998351bce3130d2ef7503a97 | 39.339695 | 118 | 0.649163 | false | false | false | false |
andreyvit/ExpressiveCollections.swift | refs/heads/master | Source/Algorithms.swift | mit | 1 | import Foundation
public extension SequenceType {
/// Find the first element passing the given test
public func find(@noescape test: (Generator.Element) throws -> Bool) rethrows -> Generator.Element? {
for item in self {
if try test(item) {
return item
}
}
return nil
}
/// Like map, but the transform can return `nil` to skip elements.
public func mapIf<U>(@noescape transform: (Generator.Element) throws -> U?) rethrows -> [U] {
var result: [U] = []
result.reserveCapacity(underestimateCount())
for el in self {
let optionalOutput = try transform(el)
if let output = optionalOutput {
result.append(output)
}
}
return result
}
/// Find the first element for which the given function returns a non-nil result, and return that result.
public func findMapped<U>(@noescape transform: (Generator.Element) throws -> U?) rethrows -> U? {
for el in self {
if let output = try transform(el) {
return output
}
}
return nil
}
/// Checks if all elements pass the given test.
public func all(@noescape test: (Generator.Element) throws -> Bool) rethrows -> Bool {
for item in self {
if !(try test(item)) {
return false
}
}
return true
}
// looking for any()? see contains() in stdlib
/// Returns a dictionary with elements keyed by the value of the given function.
public func indexBy<K>(@noescape keyFunc: (Generator.Element) throws -> K?) rethrows -> [K: Generator.Element] {
var result: [K: Generator.Element] = [:]
for item in self {
if let key = try keyFunc(item) {
result[key] = item
}
}
return result
}
}
public extension SequenceType where Generator.Element: CollectionType {
/// Turns an array of arrays into a flat array.
public func flatten() -> [Generator.Element.Generator.Element] {
var items: [Generator.Element.Generator.Element] = []
for subsequence in self {
items.appendContentsOf(subsequence)
}
return items
}
/// Turns an array of arrays into a flat array, interposing a separator element returned by the given function between each non-empty group.
public func flattenWithSeparator(@noescape separator: () throws -> Generator.Element.Generator.Element) rethrows -> [Generator.Element.Generator.Element] {
var result: [Generator.Element.Generator.Element] = []
var separatorRequired = false
for group in self {
if group.isEmpty {
continue;
}
if separatorRequired {
result.append(try separator())
}
result.appendContentsOf(group)
separatorRequired = true
}
return result
}
/// Turns an array of arrays into a flat array, interposing a given separator element between each non-empty group.
public func flattenWithSeparator(separator: Generator.Element.Generator.Element) -> [Generator.Element.Generator.Element] {
var result: [Generator.Element.Generator.Element] = []
var separatorRequired = false
for group in self {
if group.isEmpty {
continue;
}
if separatorRequired {
result.append(separator)
}
result.appendContentsOf(group)
separatorRequired = true
}
return result
}
}
public extension RangeReplaceableCollectionType where Generator.Element: Equatable {
/// Removes the given element from the collection, if it exists. If multiple elements are found, only the first one is removed.
public mutating func removeElement(element: Generator.Element) {
if let index = self.indexOf(element) {
self.removeAtIndex(index)
}
}
/// Removes the given elements from the collection. Only the first occurrence of each element is removed.
public mutating func removeElements<S: SequenceType where S.Generator.Element == Generator.Element>(elements: S) {
for item in elements {
removeElement(item)
}
}
/// If `!self.isEmpty`, remove the last element and return it, otherwise
/// return `nil`.
public mutating func popFirst() -> Generator.Element? {
if isEmpty {
return nil
} else {
return removeFirst()
}
}
}
public extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
/// Removes the elements passing the given test from the collection.
public mutating func removeElements(@noescape predicate: (Generator.Element) throws -> Bool) rethrows {
let start = startIndex
var cur = endIndex
while cur != start {
if try predicate(self[cur]) {
removeAtIndex(cur)
}
--cur
}
}
}
| e0bcdfb95417e3b87a6a2d3c3d139731 | 32.019231 | 159 | 0.600466 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/main | Shared/Extensions/HashExtensions.swift | mpl-2.0 | 7 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension Data {
public var sha1: Data {
let len = Int(CC_SHA1_DIGEST_LENGTH)
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity: len)
CC_SHA1((self as NSData).bytes, CC_LONG(self.count), digest)
return Data(bytes: UnsafePointer<UInt8>(digest), count: len)
}
public var sha256: Data {
let len = Int(CC_SHA256_DIGEST_LENGTH)
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity: len)
CC_SHA256((self as NSData).bytes, CC_LONG(self.count), digest)
return Data(bytes: UnsafePointer<UInt8>(digest), count: len)
}
}
extension String {
public var sha1: Data {
let data = self.data(using: .utf8)!
return data.sha1
}
public var sha256: Data {
let data = self.data(using: .utf8)!
return data.sha256
}
}
extension Data {
public func hmacSha256WithKey(_ key: Data) -> Data {
let len = Int(CC_SHA256_DIGEST_LENGTH)
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity: len)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256),
(key as NSData).bytes, Int(key.count),
(self as NSData).bytes, Int(self.count),
digest)
return Data(bytes: UnsafePointer<UInt8>(digest), count: len)
}
}
extension String {
public var utf8EncodedData: Data {
return self.data(using: .utf8, allowLossyConversion: false)!
}
}
extension Data {
public var utf8EncodedString: String? {
return String(data: self, encoding: .utf8)
}
}
| 2725db09c84bce7245b83674f062de10 | 28.983051 | 72 | 0.63991 | false | false | false | false |
jneyer/SimpleRestClient | refs/heads/master | SimpleRestClient/Classes/SimpleRestClient.swift | mit | 1 | //
// SimpleRestClient.swift
// Pods
//
// Created by John Neyer on 8/24/17.
//
//
import Foundation
import PromiseKit
import Alamofire
import ObjectMapper
class SimpleRestClient : NSObject {
private var url : String;
private var apiKey : String?;
private var headers : HTTPHeaders?;
private init(url: String, apiKey: String?) {
self.url = url;
HTTPRouter.baseURLString = url
if (apiKey != nil) {
self.apiKey = apiKey;
headers = [
"x-api-key": apiKey!,
"Accept": "application/json"
]
}
}
public static func defaultClient(url: String, apiKey: String?) -> SimpleRestClient {
return SimpleRestClient(url: url, apiKey: apiKey);
}
//HTTP operations
public func get<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> {
return self.httpRequest(method: .get, route: route, parameters : parameters, pathParams: pathParams);
}
public func post<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> {
return self.httpRequest(method: .post, route: route, parameters: parameters)
}
public func put<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> {
return self.httpRequest(method: .put, route: route, parameters: parameters)
}
public func delete<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> {
return self.httpRequest(method: .delete, route: route, parameters: parameters)
}
private func httpRequest<T : Mappable>(method : HTTPMethod, route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams: String? = nil) -> Promise<T?> {
return Promise<T?> { (fulfill, reject) -> Void in
func parsingError(erroString : String) -> NSError {
return NSError(domain: "org.septa.SimpleRestClient", code: -100, userInfo: nil)
}
var route = route.URLString;
if let pparams = pathParams {
route = route + "/" + pparams;
}
request(route, method: method, parameters: parameters, headers: headers).responseJSON { (response) -> Void in
// debugPrint(response.result.value ?? "Warning: empty response") // dump the response
if let error = response.result.error {
reject(error) //network error
}
else {
if let apiResponse = Mapper<T>().map(JSONObject: response.result.value)
{
let status = apiResponse as? RestResponse
if (status != nil && status!.success)
{
fulfill(apiResponse)
}
else {
if let logicalerror = status?.error {
reject(ErrorResult(errorFromAPI: logicalerror))
}
else {
reject(ErrorResult(errorFromAPI: nil))
}
}
}
else {
let err = NSError(domain: "org.septa.SimpleRestClient", code: -101, userInfo: nil)
reject(err)
}
}
}
}
}
}
| eb8f531a25ed74796e9ce467c846ac7a | 35.150943 | 169 | 0.504697 | false | false | false | false |
KlubJagiellonski/pola-ios | refs/heads/master | BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/OwnBrandContent/OwnBrandContentViewController.swift | gpl-2.0 | 1 | import UIKit
class OwnBrandContentViewController: UIViewController {
let result: ScanResult
private var ownBrandView: OwnBrandContentView! {
view as? OwnBrandContentView
}
init(result: ScanResult) {
self.result = result
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = OwnBrandContentView()
}
override func viewDidLoad() {
super.viewDidLoad()
guard let companies = result.companies,
companies.count == 2 else {
return
}
setupCompanyTitleView(ownBrandView.primaryCompanyTitleView, company: companies[1])
setupCompanyTitleView(ownBrandView.secondaryCompanyTitleView, company: companies[0])
ownBrandView.descriptionView.text = companies[0].description
}
private func setupCompanyTitleView(_ titleView: OwnBrandCompanyTitleView, company: Company) {
titleView.title = company.name
if let score = company.plScore {
titleView.progress = CGFloat(score) / 100.0
} else {
titleView.progress = 0
}
}
}
| 7b7eeb0a9350e6c8ebfbd6b3f00a5d02 | 27.155556 | 97 | 0.644041 | false | false | false | false |
sacrelee/iOSDev | refs/heads/master | Notes/Swift/Coding.playground/Pages/Generics.xcplaygroundpage/Contents.swift | apache-2.0 | 1 | /// 泛型 Generics
/*
泛型代码可以让你写出根据自我需求定义、适用于任何类型的,灵活且可重用的函数和类型。
可以避免重复代码,用清晰和抽象的方式来表达代码意图
*/
/// 泛型所解决的问题
// ①此例为非泛型函数,用来交换两个Int值
func swapTwoInts( inout a:Int, inout _ b:Int){
let temp = a
a = b
b = temp
}
var a = 3, b = 8
swapTwoInts(&a, &b)
print("Now a:\(a), b:\(b)")
// *更多例子
// ②这个函数交换两个字符串的值
func swapTwoStrings( inout a:String, inout _ b:String){
let temp = a
a = b
b = temp
}
// ③这个函数交换两个Double类型值
func swapTwoDoubles( inout a:Double, inout _ b:Double){
let temp = a
a = b
b = temp
}
/*
以上①②③三个函数,除了传入参数的类型不同,所做的事情是一样的,所以我们需要有一个泛型函数来代替这三个函数
PS:在所有三个函数中,a和b的类型是一样的。如果a和b不是相同的类型,那它们俩就不能互换值。Swift 是类型安全的语言,所以它不允许一个String类型的变量和一个Double类型的变量互相交换值。如果一定要做,Swift 将报编译错误。
*/
/// 泛型函数
// *以上函数的泛型版本
// <>中的T,是一个占位类型名(一般用T表示),参数后的T表示这两个参数是同一类型
func swapTwoValues<T>( inout a:T, inout _ b:T){
let temp = a
a = b
b = temp
}
var someInt = 3, anotherInt = 10
swapTwoValues( &someInt, &anotherInt) // 参数为Int型
print("Now someInt: \(someInt), anotherInt: \(anotherInt)")
var aString = "hello", bString = "world"
swapTwoValues( &aString, &bString) // 参数为String型
print("aString: \(aString), bString: \(bString)")
/// 类型参数
/* ①占位类型T是一种类型参数的示例。
②类型参数被指定,就可以作为参数,返回值或者函数主体中的注释类型。函数被调用时,类型参数就会被实际参数类型所替换(在上面swapTwoValues例子中,当函数第一次被调用时,T被Int替换,第二次调用时,被String替换。)
③你可支持多个类型参数,命名在尖括号中,用逗号分开。
*/
/// 命名类型参数
/*
在简单的情况下,泛型函数或泛型类型需要指定一个占位类型(如上面的swapTwoValues泛型函数,或一个存储单一类型的泛型集,如数组),通常用一单个字母T来命名类型参数。不过,你可以使用任何有效的标识符来作为类型参数名。
如果你使用多个参数定义更复杂的泛型函数或泛型类型,那么使用更多的描述类型参数是非常有用的。例如,Swift 字典(Dictionary)类型有两个类型参数,一个是键,另外一个是值。如果你自己写字典,你或许会定义这两个类型参数为Key和Value,用来记住它们在你的泛型代码中的作用。
PS:请始终使用大写字母开头的驼峰式命名法(例如T和Key)来给类型参数命名,以表明它们是类型的占位符,而非类型值。
*/
/// 泛型类型
// 通常在泛型函数中,Swift 允许你定义你自己的泛型类型。这些自定义类、结构体和枚举作用于任何类型.
// ①Int类型栈,遵循先进后出的原则
struct IntStack {
var items = [Int]()
mutating func push( item:Int){ // push一个元素入栈,(新入栈总是在最后)
items.append( item)
}
mutating func pop() -> Int{ // pop一个元素出栈,(总是最后一个)
return items.removeLast()
}
}
// ②同上功能的一个泛型版本
struct Stack<T>{ // <>内的泛型参数
var items = [T]() // 数组内元素为泛型类型
mutating func push( item:T){ // push一个泛型元素
items.append( item)
}
mutating func pop() -> T{ // pop一个泛型元素
return items.removeLast()
}
}
var stackOfString = Stack<String>() // String类型的栈
stackOfString.push("Google")
stackOfString.push("Apple")
stackOfString.push("Microsoft")
stackOfString.push("IBM")
stackOfString.push("Yahoo") // push 5个元素
stackOfString.pop() // pop掉一个元素
/// 扩展一个泛型类型
/*
当你扩展一个泛型类型的时候,你并不需要在扩展的定义中提供类型参数列表。更加方便的是,原始类型定义中声明的类型参数列表在扩展里是可以使用的,并且这些来自原始类型中的参数名称会被用作原始定义中类型参数的引用。
*/
extension Stack{
var topItem:T?{ // 泛型类型"T"可以被直接使用,
return items.isEmpty ? nil: items[items.count - 1] // 如果items数组为空,返回空,否则返回最后一个元素
}
}
if let topItem = stackOfString.topItem {
print("The top item is: \(stackOfString.topItem)")
}
/// 类型约束
/*
类型约束指定了一个必须继承自指定类的类型参数,或者遵循一个特定的协议或协议构成。
例如,Swift 的Dictionary类型对作用于其键的类型做了些限制。在字典的描述中,字典的键类型必须是可哈希,也就是说,必须有一种方法可以使其被唯一的表示。这样字典可以唯一确定键。
*/
// *类型约束语法
/*
你可以写一个在一个类型参数名后面的类型约束,通过冒号分割,来作为类型参数链的一部分。这种作用于泛型函数的类型约束的基础语法如下所示(和泛型类型的语法相同):
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// 这里是函数主体
}
*/
// *类型约束实例
func findStringIndex( array:[String], _ valueToFind:String ) -> Int?{ // 查找字符串在数组中的位置
for ( index, value) in array.enumerate(){
if value == valueToFind {
return index
}
}
return nil
}
let strings = [ "Dog", "Cat", "Cow", "Pig"] // 查找Cat
if let index = findStringIndex( strings, "Cat"){
print("Index of Cat is: \(index)")
}
func findIndex<T:Equatable>( array:[T], _ valueToFind:T ) -> Int? {
for ( index, value) in array.enumerate(){
if value == valueToFind { // 如果T不遵循"Equatable"协议,这里编译不能通过,因为不是所有的传入类型都可以被编译
return index
}
}
return nil
}
// PS:Equatable协议要求所有遵循此协议的类型均实现 "==" 和 "!=",也就是说可比较的
let doubleIndex = findIndex( [ 3.1415927, 5.45], 2.67) // 返回结果 nil
let stringIndex = findIndex( ["PU", "TU", "BHU"], "TU") // 返回结果 1
/// 关联类型
/*
当定义一个协议时,有的时候声明一个或多个关联类型作为协议定义的一部分是非常有用的。一个关联类型作为协议的一部分,给定了类型的一个占位名(或别名)。作用于关联类型上实际类型在协议被实现前是不需要指定的。关联类型被指定为typealias关键字。
*/
// *关联类型实例
protocol Container{
typealias ItemType
mutating func append( item:ItemType) // 可以将元素添加到容器
var count: Int { get } // 可以获取当前元素个数
subscript( i: Int) -> ItemType { get } // 可以根据下标获取某个元素
}
struct StackOfInt:Container {
// IntStack的原始实现
var items = [Int]()
mutating func push( item: Int){
items.append( item)
}
mutating func pop() -> Int{
return items.removeLast()
}
// 遵循Container协议的实现
typealias ItemType = Int // 删掉这一行也没有什么问题
mutating func append(item: Int) {
self.push( item)
}
var count: Int{
return items.count
}
subscript( i: Int) -> Int{
return items[i]
}
}
// 由于IntStack遵循Container协议的所有要求,只要通过简单的查找append(_:)方法的item参数类型和下标返回的类型,Swift就可以推断出合适的ItemType来使用。
struct StackWithContainer<T>:Container { // 泛型版本遵循Container协议的栈
var items = [T]()
mutating func push( item:T){
items.append(item)
}
mutating func pop() -> T{
return items.removeLast()
}
mutating func append(item: T) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
// *扩展一个存在的类型为一指定关联类型
/*
在扩展中添加协议成员中有描述扩展一个存在的类型添加遵循一个协议。这个类型包含一个关联类型的协议。
Swift的Array已经提供append(_:)方法,一个count属性和通过下标来查找一个自己的元素。这三个功能都达到Container协议的要求。也就意味着你可以扩展Array去遵循Container协议,只要通过简单声明Array适用于该协议而已。如何实践这样一个空扩展,在通过扩展补充协议声明中有描述这样一个实现一个空扩展的行为:
extension Array: Container {}
如同上面的泛型Stack类型一样,Array的append(_:)方法和下标保证Swift可以推断出ItemType所使用的适用的类型。定义了这个扩展后,你可以将任何Array当作Container来使用。
*/
// *Where语句
/*
类型约束能够确保类型符合泛型函数或类的定义约束。
*/
extension Array: Container{}
// 这个函数用来判断符合Container协议的两个实例是否相同
func allItemsMatch<C1:Container, C2:Container where C1.ItemType == C2.ItemType, C1.ItemType:Equatable>( someContainer:C1, _ anotherContainer:C2) -> Bool{
// 检查两个Container的元素个数是否相同
if someContainer.count != anotherContainer.count {
return false
}
// 检查两个Container中相应位置的元素是否相同
for i in 0..<someContainer.count{
if someContainer[i] != anotherContainer[i]{
return false
}
}
// 如果以上判断都没问题则返回true
return true
}
/*
剖析“<>”中的条件:
①C1必须遵循Container协议 (写作 C1: Container)。
②C2必须遵循Container协议 (写作 C2: Container)。
③C1的ItemType同样是C2的ItemType(写作 C1.ItemType == C2.ItemType)。
④C1的ItemType必须遵循Equatable协议 (写作 C1.ItemType: Equatable)。
第三个和第四个要求被定义为一个where语句的一部分,写在关键字where后面,作为函数类型参数链的一部分。
以上要求的意思是:someContainer是一个C1类型的容器。 anotherContainer是一个C2类型的容器。 someContainer和anotherContainer包含相同的元素类型。 someContainer中的元素可以通过不等于操作(!=)来检查它们是否彼此不同。
第三个和第四个要求结合起来的意思是anotherContainer中的元素也可以通过 != 操作来检查,因为它们在someContainer中元素确实是相同的类型。
*/
// 判断两个遵循Container协议的实例是否相同
var stackOfStrings = StackWithContainer<String>()
stackOfStrings.push("🐶")
stackOfStrings.push("🐱")
stackOfStrings.push("🐭")
stackOfStrings.push("🐷")
var arrayOfStrings = ["🐶", "🐱", "🐭", "🐷"]
if allItemsMatch(stackOfStrings, arrayOfStrings){
print("All items match.")
}
else{
print("Not all items match.")
}
| e711af8a3511bfc3e40f5fbe9db9122a | 23.09571 | 172 | 0.684838 | false | false | false | false |
ihomway/RayWenderlichCourses | refs/heads/master | Beginning Swift 3/Beginning Swift 3.playground/Pages/Loop Challenge.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import UIKit
/*:
#### Beginning Swift Video Tutorial Series - raywenderlich.com
#### Video 7: Loops
**Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu.
*/
//: Create a loop to iterate through a range of 0 through 10 and print out the event numbers. Use a for-in loop.
for index in 0...10 {
if index % 2 == 0 {
print(index)
}
}
//: Do the same with a while loop
var temp = 0
while temp <= 10 {
if temp % 2 == 0 {
print(temp)
}
temp += 1
}
//: Do the same with a repeat-while loop
temp = 0
repeat {
if temp % 2 == 0 {
print(temp)
}
temp += 1
} while temp <= 10
//: **Ub3r H4ck3r Challenge** - Creata an outer loop to count between 1 to 10 and create an inner loop to also count to 1 to 10. Multiply the index of the outer loop with the index of the inner loop, and print out the result. The result should read: 1 * 1 = 1
//: [Next](@next)
| f66e04c6494a6ce0cd4d6e07aecf489b | 23.3 | 259 | 0.664609 | false | false | false | false |
lhx931119/DouYuTest | refs/heads/master | DouYu/DouYu/Classes/Home/Controller/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// DouYu
//
// Created by 李宏鑫 on 17/1/13.
// Copyright © 2017年 hongxinli. All rights reserved.
//
import UIKit
private let kTitleViewH: CGFloat = 40
class HomeViewController: UIViewController {
private lazy var pageTitleView:PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavgationBarH, width:kScreenW , height: kTitleViewH)
let titles = ["推荐","手游","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
titleView.backgroundColor = UIColor.whiteColor()
return titleView
}()
private lazy var pageContentView:PageContentView = {[weak self] in
let contentH = kScreenH - kStatusBarH - kNavgationBarH - kTitleViewH - kTabBarH
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavgationBarH + kTitleViewH, width: kScreenW, height: contentH)
//确定所有子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
for _ in 0...2{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
//系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置UI
setUI()
}
}
// mark: 设置UI界面
extension HomeViewController{
//设置UI
private func setUI(){
//不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//设置导航栏
setNavigationBar()
//添加TitleView
view.addSubview(pageTitleView)
//添加ContentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.purpleColor()
}
//设置NavigationBar
private func setNavigationBar(){
//设置导航栏背景颜色
self.navigationController?.navigationBar.barTintColor = UIColor.orangeColor()
//设置左侧item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "homeLogoIcon")
//设置右边item
let size = CGSize(width: 40, height: 40)
let hostoryItem = UIBarButtonItem(imageName: "viewHistoryIcon", highImageName: "", size: size)
let scanItem = UIBarButtonItem(imageName: "scanIcon", highImageName: "", size: size)
let searchItem = UIBarButtonItem(imageName: "searchBtnIcon", highImageName: "", size: size)
navigationItem.rightBarButtonItems = [hostoryItem,scanItem,searchItem]
}
}
extension HomeViewController: PageTitleViewDelegate{
func pageTitleView(titleView: PageTitleView, selectIndex: Int) {
pageContentView.setCurrenIndex(selectIndex)
}
}
extension HomeViewController: PageContentViewDelegate{
func pageContentView(pageContentView: PageContentView, progress: CGFloat, oldIndex: Int, targetIndex: Int) {
pageTitleView.setTitileOffsetX(progress, oldIndex: oldIndex, targetIndex: targetIndex)
}
}
| f7511f2172c61cf5586c5fd1fcab683c | 27.00813 | 156 | 0.641219 | false | false | false | false |
silence0201/Swift-Study | refs/heads/master | AdvancedSwift/错误处理/Higher-Order Functions and Errors.playgroundpage/Contents.swift | mit | 1 | /*:
## Higher-Order Functions and Errors
One domain where Swift's error handling unfortunately does *not* work very well
is asynchronous APIs that need to pass errors to the caller in callback
functions. Let's look at a function that asynchronously computes a large number
and calls back our code when the computation has finished:
*/
//#-hidden-code
import Foundation
//#-end-hidden-code
func compute(callback: (Int) -> ())
//#-hidden-code
{
// Dummy implementation: generate a random number
let random = Int(arc4random())
callback(random)
}
//#-end-hidden-code
/*:
We can call it by providing a callback function. The callback receives the
result as the only parameter:
*/
//#-editable-code
compute { result in
print(result)
}
//#-end-editable-code
/*:
If the computation can fail, we could specify that the callback receives an
optional integer, which would be `nil` in case of a failure:
*/
//#-editable-code
func computeOptional(callback: (Int?) -> ())
//#-end-editable-code
//#-hidden-code
{
// Dummy implementation: generate a random number, sometimes return nil
let random = Int(arc4random())
if random % 3 == 0 { callback(nil) }
else { callback(random) }
}
//#-end-hidden-code
/*:
Now, in our callback, we must check whether the optional is non-`nil`, e.g. by
using the `??` operator:
*/
//#-editable-code
computeOptional { result in
print(result ?? -1)
}
//#-end-editable-code
/*:
But what if we want to report specific errors to the callback, rather than just
an optional? This function signature seems like a natural solution:
``` swift-example
func computeThrows(callback: Int throws -> ())
```
Perhaps surprisingly, this type has a totally different meaning. Instead of
saying that the computation might fail, it expresses that the callback itself
could throw an error. This highlights the key difference that we mentioned
earlier: optionals and `Result` work on types, whereas `throws` works only on
function types. Annotating a function with `throws` means that the *function*
might fail.
It becomes a bit clearer when we try to rewrite the wrong attempt from above
using `Result`:
``` swift-example
func computeResult(callback: Int -> Result<()>)
```
This isn't correct either. We need to wrap the `Int` argument in a `Result`, not
the callback's return type. Finally, this is the correct solution:
*/
//#-hidden-code
enum Result<A> {
case failure(Error)
case success(A)
}
//#-end-hidden-code
//#-hidden-code
struct ComputeError: Error {}
//#-end-hidden-code
//#-editable-code
func computeResult(callback: (Result<Int>) -> ())
//#-end-editable-code
//#-hidden-code
{
// Dummy implementation: generate a random number, sometimes return nil
let random = Int(arc4random())
if random % 3 == 0 { callback(.failure(ComputeError())) }
else { callback(.success(random)) }
}
//#-end-hidden-code
/*:
Unfortunately, there's currently no clear way to write the variant above with
`throws`. The best we can do is wrap the `Int` inside another throwing function.
This makes the type more complicated:
``` swift-example
func compute(callback: (() throws -> Int) -> ())
```
And using this variant becomes more complicated for the caller too. In order to
get the integer out, the callback now has to call the throwing function. This is
where the caller must perform the error checking:
``` swift-example
compute { (resultFunc: () throws -> Int) in
do {
let result = try resultFunc()
print(result)
} catch {
print("An error occurred: \(error)")
}
}
```
This works, but it's definitely not idiomatic Swift; `Result` is the way to go
for asynchronous error handling. It's unfortunate that this creates an impedance
mismatch with synchronous functions that use `throws`. The Swift team has
expressed interest in extending the `throws` model to other scenarios, but this
will likely be part of the much greater task of adding native concurrency
features to the language, and that won't happen until after Swift 4.
Until then, we're stuck with using our own custom `Result` types. Apple did
consider adding a `Result` type to the standard library, but ultimately [decided
against
it](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001433.html)
on the grounds that it wasn't independently valuable enough outside the error
handling domain and that the team didn't want to endorse it as an alternative to
`throws`-style error handling. Luckily, using `Result` for asynchronous APIs is
a pretty well established practice among the Swift developer community, so you
shouldn't hesitate to use it in your APIs when the native error handling isn't
appropriate. It certainly beats the Objective-C style of having completion
handlers with two nullable arguments (a result object and an error object).
*/
| 39df9ca2ad5a9c9869779efaf664d7c1 | 28.888889 | 87 | 0.731929 | false | false | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/Data/DPolynomialExtension.swift | mit | 1 | import Foundation
import CoreData
extension DPolynomial
{
//MARK: public
func coefficient() -> Double
{
let sign:Double
if isPositive
{
sign = 1
}
else
{
sign = -1
}
var coefficientValue:Double = coefficientDividend / coefficientDivisor
coefficientValue *= sign
return coefficientValue
}
func inversed() -> DPolynomial?
{
let managedObject:NSManagedObject = NSManagedObject(
entity:entity,
insertInto:nil)
guard
let polynomial:DPolynomial = managedObject as? DPolynomial
else
{
return nil
}
polynomial.coefficientDividend = coefficientDividend
polynomial.coefficientDivisor = coefficientDivisor
polynomial.isPositive = !isPositive
return polynomial
}
func signedDividend() -> Double
{
let sign:Double
if isPositive
{
sign = 1
}
else
{
sign = -1
}
let signed:Double = coefficientDividend * sign
return signed
}
func add(polynomial:DPolynomial)
{
let dividend:Double = signedDividend()
let polynomialDividend:Double = polynomial.signedDividend()
let polynomialDivisor:Double = polynomial.coefficientDivisor
if coefficientDivisor == polynomialDivisor
{
let newDividend:Double = dividend + polynomialDividend
coefficientDividend = abs(newDividend)
if newDividend < 0
{
isPositive = false
}
else
{
isPositive = true
}
}
else
{
let newDivisor:Double = coefficientDivisor * polynomialDivisor
let newDividend:Double = dividend * polynomialDivisor
let newPolynomialDividend:Double = polynomialDividend * coefficientDivisor
let totalDividend:Double = newDividend + newPolynomialDividend
coefficientDividend = abs(totalDividend)
coefficientDivisor = newDivisor
if totalDividend < 0
{
isPositive = false
}
else
{
isPositive = true
}
showAsDivision = true
}
}
func deleteFromEquation()
{
if let equationResult:DEquation = self.equationResult
{
guard
let countPolynomials:Int = equationResult.polynomials?.count
else
{
return
}
if countPolynomials > 0
{
equationResult.restartResult()
}
else
{
guard
let project:DProject = equationResult.project
else
{
return
}
project.deleteEquation(equation:equationResult)
}
}
else if let equationPolynomials:DEquation = self.equationPolynomials
{
equationPolynomials.deletePolynomial(polynomial:self)
}
}
}
| a1042c17025b1536245b2d6ee0a21347 | 23.267123 | 86 | 0.482642 | false | false | false | false |
toshiapp/toshi-ios-client | refs/heads/master | Toshi/Controllers/Sign In/SplashNavigationController.swift | gpl-3.0 | 1 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
class SplashNavigationController: UINavigationController {
convenience init() {
self.init(rootViewController: SplashViewController())
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.barStyle = .default
navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
navigationBar.shadowImage = UIImage()
let titleTextAttributes: [NSAttributedStringKey: Any] = [
.font: Theme.regular(size: 17),
.foregroundColor: Theme.darkTextColor
]
navigationBar.titleTextAttributes = titleTextAttributes
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return viewControllers.count == 1 ? .lightContent : .default
}
}
| 75d216d5eaff6e0a30c719b2a83f80b0 | 34.904762 | 84 | 0.694297 | false | false | false | false |
fonesti/EasyTimer | refs/heads/master | EasyTimer-iOSDemo/FirstViewController.swift | mit | 1 | //
// FirstViewController.swift
// EasyTimer-iOSDemo
//
// Created by Filippo Onesti on 26/06/2017.
// Copyright © 2017 Károly Lőrentey. All rights reserved.
//
import UIKit
import EasyTimer
class FirstViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!{
didSet{
self.timeLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 50, weight: .regular)
}
}
@IBOutlet weak var elapsedLabel: UILabel!{
didSet{
self.elapsedLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 17, weight: .regular)
}
}
@IBOutlet weak var remainingLabel: UILabel!{
didSet{
self.remainingLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 17, weight: .regular)
}
}
@IBOutlet weak var button: UIButton!
var timer: EasyTimer!
override func viewDidLoad() {
super.viewDidLoad()
self.timer = EasyTimer(timerFrom: TimeInterval(hours: 0, minutes: 0, seconds: 120), updateBlock: { (timer) in
self.timeLabel.text = timer.defaultFormattedString(timer.displayTime)
self.elapsedLabel.text = timer.defaultFormattedString(timer.elapsed)
self.remainingLabel.text = timer.defaultFormattedString(timer.remaining)
}, targetAchievedBlock: { (_) in
self.timeLabel.textColor = .green
self.button.setTitle("Start", for: .normal)
})
self.timer = EasyTimer(stopwatchUntil: 10, updateBlock: { (_) in
// Update UI
}, targetAchievedBlock: { (_) in
// Finish!
})
self.timer = EasyTimer(countdown: true, startTime: 10, endTime: 0, updateEvent: .seconds, updateBlock: { (timer) in
/// Use monospaced font with time label
// self.timeLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 20, weight: .regular)
// update UI
self.timeLabel.text = timer.defaultFormattedString(timer.displayTime)
self.elapsedLabel.text = timer.defaultFormattedString(timer.elapsed)
self.remainingLabel.text = timer.defaultFormattedString(timer.remaining)
}, targetAchievedBlock: { (timer) in
// Finish!
self.timeLabel.textColor = .green
self.button.setTitle("Start", for: .normal)
})
self.timer.updateBlock?(self.timer)
}
@IBAction func toggleAction(_ sender: UIButton) {
if (self.timer.isRunning){
self.timer.pause()
sender.setTitle("Start", for: .normal)
}
else{
self.timer.resume()
sender.setTitle("Pause", for: .normal)
}
}
@IBAction func ResetAction(_ sender: UIButton) {
self.timer.reset()
button.setTitle("Start", for: .normal)
}
@IBAction func toggleFormat(_ sender: UISwitch) {
self.timer.updateEvent = self.timer.updateEvent == .seconds ? .centiseconds : .seconds
self.timer.defaultDateFormatter.dateFormat = self.timer.defaultDateFormatter.dateFormat == EasyTimer.DateFormat.mm_ss_SS ? EasyTimer.DateFormat.mm_ss : EasyTimer.DateFormat.mm_ss_SS
}
}
| 6695964dca0f5a4cf94c4aeb349c8b55 | 33.21875 | 189 | 0.609437 | false | false | false | false |
kzaher/RxFirebase | refs/heads/master | RxFirebase/Classes/FIRDatabaseQuery+Extensions.swift | mit | 2 | //
// RxFirebaseDatabase.swift
// Pods
//
// Created by David Wong on 19/05/2016.
//
//
import FirebaseDatabase
import RxSwift
public extension Reactive where Base: FIRDatabaseQuery {
/**
Listen for data changes at a particular location.
This is the primary way to read data from the Firebase Database. The observers
will be triggered for the initial data and again whenever the data changes.
@param eventType The type of event to listen for.
*/
func observe(_ eventType: FIRDataEventType) -> Observable<FIRDataSnapshot> {
return Observable.create { observer in
let handle = self.base.observe(eventType, with: observer.onNext, withCancel: observer.onError)
return Disposables.create {
self.base.removeObserver(withHandle: handle)
}
}
}
/**
Listen for data changes at a particular location. This is the primary way to read data from
the Firebase Database. The observers will be triggered for the initial data and again
whenever the data changes. In addition, for FIRDataEventTypeChildAdded,FIRDataEventTypeChildMoved
and FIRDataEventTypeChildChanged, your block will be passed the key of the previous node by
priority order.
@param eventType The type of event to listen for.
*/
func observeWithPreviousSiblingKey(_ eventType: FIRDataEventType) -> Observable<(FIRDataSnapshot, String?)> {
return Observable.create { observer in
let handle = self.base.observe(eventType,
andPreviousSiblingKeyWith: observer.onNext,
withCancel: observer.onError)
return Disposables.create {
self.base.removeObserver(withHandle: handle)
}
}
}
/**
This is equivalent to observe(), except the observer is immediately canceled after the initial data is returned.
@param eventType The type of event to listen for.
*/
func observeSingleEvent(of eventType: FIRDataEventType) -> Observable<FIRDataSnapshot> {
return Observable.create { observer in
self.base.observeSingleEvent(of: eventType, with: { (snapshot) in
observer.onNext(snapshot)
observer.onCompleted()
}, withCancel: observer.onError)
return Disposables.create()
}
}
/**
This is equivalent to observeWithSiblingKey(), except the observer is immediately
canceled after the initial data is returned.
@param eventType The type of event to listen for.
*/
func observeSingleEvent(of eventType: FIRDataEventType) -> Observable<(FIRDataSnapshot, String?)> {
return Observable.create { observer in
self.base.observeSingleEvent(of: eventType, andPreviousSiblingKeyWith: { (snapshot, string) in
observer.onNext((snapshot, string))
observer.onCompleted()
}, withCancel: observer.onError)
return Disposables.create()
}
}
}
public extension Reactive where Base: FIRDatabaseReference {
/**
Update changes the values at the specified paths in the dictionary without
overwriting other keys at this location
@param values A dictionary of keys to change and their new values
*/
func updateChildValues(_ values: [AnyHashable : Any]) -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.updateChildValues(values, withCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Write data to this Firebase Database location.
This will overwrite any data at this location and all child locations.
Data types that can be set are:
- String / NSString
- NSNumber
- Dictionary<String: AnyObject> / NSDictionary
- Array<Above objects> / NSArray
The effect of the write will be visible immediately and the correspoding
events will be triggered. Synchronization of the data to the Firebase Database
servers will also be started.
Passing null for the new value is equivalent to calling remove()
all data at this location or any child location will be deleted.
Note that setValue() will remove any priority stored at this location,
so if priority is meant to be preserved, you should use setValue(value:, priority:) instead.
@param value The value to be written
@param priority The Priority to be attached to the data.
*/
func setValue(_ value: Any?, priority: Any? = nil) -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.setValue(value, andPriority: priority, withCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Remove the data at this Firebase Database location. Any data at child locations will also be deleted.
The effect of the delete will be visible immediately and the corresponding events
will be triggered. Synchronization of the delete to the Firebase Database servers will
also be started.
*/
func removeValue() -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.removeValue(completionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData
instance that contains the current data at this location. Your block should update this data to the value you
wish to write to this location, and then return an instance of FIRTransactionResult with the new data.
If, when the operation reaches the server, it turns out that this client had stale data, your block will be run again with the latest data from the server.
When your block is run, you may decide to aport the traansaction by return FIRTransactionResult.abort()
@param block This block receives the current data at this location and must return an instance of FIRTransactionResult
*/
func runTransactionBlock(block: @escaping ((FIRMutableData) -> FIRTransactionResult)) -> Observable<(Bool, FIRDataSnapshot)> {
return Observable.create { observer in
self.base.runTransactionBlock(block, andCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Set a priority for the data at this Firebase Database location.
Priorities can be used to provide a custom ordering for the children at a location
(if no priorities are specified, the children are ordered by key).
You cannot set a priority on an empty location. For this reason
setValue:andPriority: should be used when setting initial data with a specific priority
and setPriority: should be used when updating the priority of existing data.
Children are sorted based on this priority using the following rules:
Children with no priority come first.
Children with a number as their priority come next. They are sorted numerically by priority (small to large).
Children with a string as their priority come last. They are sorted lexicographically by priority.
Whenever two children have the same priority (including no priority), they are sorted by key. Numeric
keys come first (sorted numerically), followed by the remaining keys (sorted lexicographically).
Note that priorities are parsed and ordered as IEEE 754 double-precision floating-point numbers.
Keys are always stored as strings and are treated as numbers only when they can be parsed as a
32-bit integer
@param priority The priority to set at the specified location.
*/
func setPriority(priority : Any?) -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.setPriority(priority, withCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Ensure the data at this location is set to the specified value when
the client is disconnected (due to closing the browser, navigating
to a new page, or network issues).
onDisconnectSetValue() is especially useful for implementing "presence" systems,
where a value should be changed or cleared when a user disconnects
so that he appears "offline" to other users.
@param value The value to be set after the connection is lost.
@param priority The priority to be set after the connection is lost.
*/
func onDisconnectSetValue(_ value: Any?, andPriority priority: Any? = nil) -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.onDisconnectSetValue(value, andPriority: priority, withCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Ensure the data has the specified child values updated when
the client is disconnected (due to closing the browser, navigating
to a new page, or network issues).
@param values A dictionary of child node keys and the values to set them to after the connection is lost.
*/
func onDisconnectUpdateChildValue(_ values: [AnyHashable : Any]) -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.onDisconnectUpdateChildValues(values, withCompletionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
/**
Ensure the data t this location is removed when
the client is disconnected (due to closing the app, navigating
to a new page, or network issues
onDisconnectRemoveValue() is especially useful for implementing "presence systems.
*/
func onDisconnectRemoveValue() -> Observable<FIRDatabaseReference> {
return Observable.create { observer in
self.base.onDisconnectRemoveValue(completionBlock: parseFirebaseResponse(observer))
return Disposables.create()
}
}
}
public extension ObservableType where E : FIRDataSnapshot {
func children() -> Observable<[FIRDataSnapshot]> {
return self.map { snapshot in
guard let children = snapshot.children.allObjects as? [FIRDataSnapshot] else {
throw UnknownFirebaseError()
}
return children
}
}
}
| b89c55afae0560089ecc427d00edb2d5 | 42.672065 | 160 | 0.683879 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/SDK/OpenCL/OpenCL.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import OpenCL // Clang module
@available(OSX, introduced: 10.7)
public func clSetKernelArgsListAPPLE(
kernel: cl_kernel, _ uint: cl_uint, _ args: CVarArg...
) -> cl_int {
// The variable arguments are num_args arguments that are the following:
// cl_uint arg_indx,
// size_t arg_size,
// const void *arg_value,
return withVaList(args) { clSetKernelArgsVaListAPPLE(kernel, uint, $0) }
}
| 5dabd48f681870d4118cf51266819609 | 38.333333 | 80 | 0.583686 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/core/ArrayBuffer.swift | apache-2.0 | 2 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore>
public struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
public init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
public init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@warn_unused_result
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
var deferredTypeCheckMask : Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
@warn_unused_result
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/19915280> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
public init(_ source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
var arrayPropertyIsNativeTypeChecked : Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@warn_unused_result
mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
@warn_unused_result
mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// - Precondition: `_isBridgedToObjectiveC(Element.self)`.
/// O(1) if the element type is bridged verbatim, O(N) otherwise.
@warn_unused_result
public func _asCocoaArray() -> _NSArrayCore {
_sanityCheck(
_isBridgedToObjectiveC(Element.self),
"Array element type is not bridged to Objective-C")
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@warn_unused_result
public mutating func requestUniqueMutableBackingBuffer(
minimumCapacity minimumCapacity: Int
) -> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@warn_unused_result
public func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
internal func _typeCheckSlowPath(index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAt(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
func _typeCheck(subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in subRange {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer past-the-end of the
/// just-initialized memory.
public func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location: bounds.startIndex,
length: bounds.endIndex - bounds.startIndex)
let buffer = UnsafeMutablePointer<AnyObject>(target)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in bounds {
result.initialize(with: result.pointee)
result += 1
}
return result
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
public subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices)
if cocoaStorageBaseAddress != nil {
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress),
indices: bounds,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let boundsCount = bounds.count
let result = _ContiguousArrayBuffer<Element>(
uninitializedCount: boundsCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutablePointer(result.firstElementAddress),
range: _SwiftNSRange(
location: bounds.startIndex,
length: boundsCount))
return _SliceBuffer(result, shiftedToStartIndex: bounds.startIndex)
}
set {
fatalError("not implemented")
}
}
public var _unconditionalMutableSubscriptBaseAddress:
UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
public var firstElementAddress: UnsafeMutablePointer<Element> {
if (_fastPath(_isNative)) {
return _native.firstElementAddress
}
return nil
}
/// The number of elements the buffer stores.
public var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
internal func _checkInoutAndNativeTypeCheckedBounds(
index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
public var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@inline(__always)
@warn_unused_result
func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@inline(never)
@warn_unused_result
func _getElementSlowPath(i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAt(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
public subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
public func withUnsafeBufferPointer<R>(
@noescape body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
public mutating func withUnsafeMutableBufferPointer<R>(
@noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
firstElementAddress != nil || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
public var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
public var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
public var identity: UnsafePointer<Void> {
if _isNative {
return _native.identity
}
else {
return unsafeAddress(of: _nonNative)
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Int {
return count
}
//===--- private --------------------------------------------------------===//
typealias Storage = _ContiguousArrayStorage<Element>
public typealias NativeBuffer = _ContiguousArrayBuffer<Element>
var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
var _nonNative: _NSArrayCore {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| 5a4c8c20422b6ac550b93d1273a1e03b | 31.367505 | 80 | 0.667324 | false | false | false | false |
duliodenis/pokedex | refs/heads/master | Pokedex/Pokedex/CSVParser.swift | mit | 1 | //
// CSVParser.swift
// Pokedex
//
// Created by Dulio Denis on 11/28/15.
// Copyright © 2015 Dulio Denis. All rights reserved.
//
import Foundation
public class CSVParser {
public var headers: [String] = []
public var rows: [Dictionary<String, String>] = []
public var columns = Dictionary<String, [String]>()
var delimiter = NSCharacterSet(charactersInString: ",")
public init(content: String?, delimiter: NSCharacterSet, encoding: UInt) throws {
if let csvStringToParse = content{
self.delimiter = delimiter
let newline = NSCharacterSet.newlineCharacterSet()
var lines: [String] = []
csvStringToParse.stringByTrimmingCharactersInSet(newline).enumerateLines { line, stop in lines.append(line) }
self.headers = self.parseHeaders(fromLines: lines)
self.rows = self.parseRows(fromLines: lines)
self.columns = self.parseColumns(fromLines: lines)
}
}
public convenience init(contentsOfURL url: String) throws {
let comma = NSCharacterSet(charactersInString: ",")
let csvString: String?
do {
csvString = try String(contentsOfFile: url, encoding: NSUTF8StringEncoding)
} catch _ {
csvString = nil
};
try self.init(content: csvString,delimiter:comma, encoding:NSUTF8StringEncoding)
}
func parseHeaders(fromLines lines: [String]) -> [String] {
return lines[0].componentsSeparatedByCharactersInSet(self.delimiter)
}
func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] {
var rows: [Dictionary<String, String>] = []
for (lineNumber, line) in lines.enumerate() {
if lineNumber == 0 {
continue
}
var row = Dictionary<String, String>()
let values = line.componentsSeparatedByCharactersInSet(self.delimiter)
for (index, header) in self.headers.enumerate() {
if index < values.count {
row[header] = values[index]
} else {
row[header] = ""
}
}
rows.append(row)
}
return rows
}
func parseColumns(fromLines lines: [String]) -> Dictionary<String, [String]> {
var columns = Dictionary<String, [String]>()
for header in self.headers {
let column = self.rows.map { row in row[header] != nil ? row[header]! : "" }
columns[header] = column
}
return columns
}
}
| bb8fa242428f05aa47bcd6a74420a2ab | 31.178571 | 121 | 0.567148 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | stdlib/public/Darwin/Accelerate/vDSP_FillClearGenerate.swift | apache-2.0 | 8 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Types that support vectorized window generation.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol vDSP_FloatingPointGeneratable: BinaryFloatingPoint {
}
extension Float: vDSP_FloatingPointGeneratable {}
extension Double: vDSP_FloatingPointGeneratable {}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vDSP {
/// Fill vector with specified scalar value, single-precision.
///
/// - Parameter vector: The vector to fill.
/// - Parameter value: The fill value.
@inlinable
public static func fill<V>(_ vector: inout V,
with value: Float)
where V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
withUnsafePointer(to: value) {
vDSP_vfill($0,
v.baseAddress!, 1,
n)
}
}
}
/// Fill vector with specified scalar value, double-precision.
///
/// - Parameter vector: The vector to fill.
/// - Parameter value: The fill value.
@inlinable
public static func fill<V>(_ vector: inout V,
with value: Double)
where V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
withUnsafePointer(to: value) {
vDSP_vfillD($0,
v.baseAddress!, 1,
n)
}
}
}
/// Fill vector with zeros, single-precision.
///
/// - Parameter vector: The vector to fill.
@inlinable
public static func clear<V>(_ vector: inout V)
where V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vclr(v.baseAddress!, 1,
n)
}
}
/// Fill vector with zeros, double-precision.
///
/// - Parameter vector: The vector to fill.
@inlinable
public static func clear<V>(_ vector: inout V)
where V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vclrD(v.baseAddress!, 1,
n)
}
}
/// Enum specifying window sequence.
public enum WindowSequence {
/// Creates a normalized Hanning window.
case hanningNormalized
/// Creates a denormalized Hanning window.
case hanningDenormalized
/// Creates a Hamming window.
case hamming
/// Creates a Blackman window.
case blackman
}
/// Creates an array containing the specified window.
///
/// - Parameter ofType: Specifies single- or double-precision.
/// - Parameter sequence: Specifies the window sequence.
/// - Parameter count: The number of elements in the array.
/// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points.
/// - Returns: An array containing the specified window.
@inlinable
public static func window<T: vDSP_FloatingPointGeneratable>(ofType: T.Type,
usingSequence sequence: WindowSequence,
count: Int,
isHalfWindow: Bool) -> [T] {
precondition(count > 0)
if T.self == Float.self {
let result = Array<Float>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formWindow(usingSequence: sequence,
result: &buffer,
isHalfWindow: isHalfWindow)
initializedCount = count
}
return result as! [T]
} else if T.self == Double.self {
let result = Array<Double>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formWindow(usingSequence: sequence,
result: &buffer,
isHalfWindow: isHalfWindow)
initializedCount = count
}
return result as! [T]
} else {
fatalError("This operation only supports `Float` and `Double` types.")
}
}
/// Fills a supplied array with the specified window, single-precision.
///
/// - Parameter sequence: Specifies the window sequence.
/// - Parameter result: Output values.
/// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points.
public static func formWindow<V>(usingSequence sequence: WindowSequence,
result: inout V,
isHalfWindow: Bool)
where V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { v in
switch sequence {
case .hanningNormalized:
vDSP_hann_window(v.baseAddress!,
n,
Int32(vDSP_HANN_NORM) |
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .hanningDenormalized:
vDSP_hann_window(v.baseAddress!,
n,
Int32(vDSP_HANN_DENORM) |
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .hamming:
vDSP_hamm_window(v.baseAddress!,
n,
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .blackman:
vDSP_blkman_window(v.baseAddress!,
n,
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
}
}
}
/// Fills a supplied array with the specified window, double-precision.
///
/// - Parameter sequence: Specifies the window sequence.
/// - Parameter result: Output values.
/// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points.
public static func formWindow<V>(usingSequence sequence: WindowSequence,
result: inout V,
isHalfWindow: Bool)
where V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { v in
switch sequence {
case .hanningNormalized:
vDSP_hann_windowD(v.baseAddress!,
n,
Int32(vDSP_HANN_NORM) |
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .hanningDenormalized:
vDSP_hann_windowD(v.baseAddress!,
n,
Int32(vDSP_HANN_DENORM) |
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .hamming:
vDSP_hamm_windowD(v.baseAddress!,
n,
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
case .blackman:
vDSP_blkman_windowD(v.baseAddress!,
n,
Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0))
}
}
}
// MARK: Ramps
//===----------------------------------------------------------------------===//
// withInitialValue and increment
//===----------------------------------------------------------------------===//
/// Returns an array containing monotonically incrementing or decrementing values, single-precision.
///
/// - Parameter initialValue: Specifies the initial value.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp(withInitialValue initialValue: Float,
increment: Float,
count: Int) -> [Float] {
precondition(count > 0)
let result = Array<Float>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formRamp(withInitialValue: initialValue,
increment: increment,
result: &buffer)
initializedCount = count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values, single-precision.
///
/// - Parameter initialValue: Specifies the initial value.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<V>(withInitialValue initialValue: Float,
increment: Float,
result: inout V)
where V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(result.count)
withUnsafePointer(to: initialValue) { a in
withUnsafePointer(to: increment) { b in
result.withUnsafeMutableBufferPointer { c in
vDSP_vramp(a,
b,
c.baseAddress!, 1,
n)
}
}
}
}
/// Returns an array containing monotonically incrementing or decrementing values, double-precision.
///
/// - Parameter initialValue: Specifies the initial value.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp(withInitialValue initialValue: Double,
increment: Double,
count: Int) -> [Double] {
precondition(count > 0)
let result = Array<Double>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formRamp(withInitialValue: initialValue,
increment: increment,
result: &buffer)
initializedCount = count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values, double-precision.
///
/// - Parameter initialValue: Specifies the initial value.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<V>(withInitialValue initialValue: Double,
increment: Double,
result: inout V)
where V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(result.count)
withUnsafePointer(to: initialValue) { a in
withUnsafePointer(to: increment) { b in
result.withUnsafeMutableBufferPointer { c in
vDSP_vrampD(a,
b,
c.baseAddress!, 1,
n)
}
}
}
}
//===----------------------------------------------------------------------===//
// range
//===----------------------------------------------------------------------===//
/// Returns an array containing monotonically incrementing or decrementing values within a specified range, single-precision.
///
/// - Parameter range: Specifies range of the ramp..
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp(in range: ClosedRange<Float>,
count: Int) -> [Float] {
precondition(count > 0)
let result = Array<Float>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formRamp(in: range,
result: &buffer)
initializedCount = count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values within a specified range, single-precision.
///
/// - Parameter range: Specifies range of the ramp.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<V>(in range: ClosedRange<Float>,
result: inout V)
where V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(result.count)
withUnsafePointer(to: range.lowerBound) { a in
withUnsafePointer(to: range.upperBound) { b in
result.withUnsafeMutableBufferPointer { c in
vDSP_vgen(a,
b,
c.baseAddress!, 1,
n)
}
}
}
}
/// Returns an array containing monotonically incrementing or decrementing values within a specified range, double-precision.
///
/// - Parameter range: Specifies range of the ramp..
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp(in range: ClosedRange<Double>,
count: Int) -> [Double] {
precondition(count > 0)
let result = Array<Double>(unsafeUninitializedCapacity: count) {
buffer, initializedCount in
formRamp(in: range,
result: &buffer)
initializedCount = count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values within a specified range, double-precision.
///
/// - Parameter range: Specifies range of the ramp.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<V>(in range: ClosedRange<Double>,
result: inout V)
where V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(result.count)
withUnsafePointer(to: range.lowerBound) { a in
withUnsafePointer(to: range.upperBound) { b in
result.withUnsafeMutableBufferPointer { c in
vDSP_vgenD(a,
b,
c.baseAddress!, 1,
n)
}
}
}
}
//===----------------------------------------------------------------------===//
// initialValue, multiplyingBy, and increment
//===----------------------------------------------------------------------===//
/// Returns an array containing monotonically incrementing or decrementing values, multiplying by a source vector, single-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplyingBy: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp<U>(withInitialValue initialValue: inout Float,
multiplyingBy vector: U,
increment: Float) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
formRamp(withInitialValue: &initialValue,
multiplyingBy: vector,
increment: increment,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, single-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplyingBy: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<U,V>(withInitialValue initialValue: inout Float,
multiplyingBy vector: U,
increment: Float,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(vector.count == result.count)
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
withUnsafePointer(to: increment) { step in
vDSP_vrampmul(src.baseAddress!, 1,
&initialValue,
step,
dest.baseAddress!, 1,
n)
}
}
}
}
/// Returns an array containing monotonically incrementing or decrementing values, multiplying by a source vector, double-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplyingBy: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements
/// - Parameter count: The number of elements in the array.
/// - Returns: An array containing the specified ramp.
@inlinable
public static func ramp<U>(withInitialValue initialValue: inout Double,
multiplyingBy vector: U,
increment: Double) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
formRamp(withInitialValue: &initialValue,
multiplyingBy: vector,
increment: increment,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, double-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplyingBy: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter result: Output values.
@inlinable
public static func formRamp<U,V>(withInitialValue initialValue: inout Double,
multiplyingBy vector: U,
increment: Double,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(vector.count == result.count)
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
withUnsafePointer(to: increment) { step in
vDSP_vrampmulD(src.baseAddress!, 1,
&initialValue,
step,
dest.baseAddress!, 1,
n)
}
}
}
}
//===----------------------------------------------------------------------===//
// stereo
//===----------------------------------------------------------------------===//
/// Returns two arraya containing monotonically monotonically incrementing or decrementing values, multiplying by a source vector, stereo, single-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplierOne: Input values multiplied by the ramp function.
/// - Parameter multiplierTwo: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Returns: A tuple of two arrays containing the specified ramps.
@inlinable
public static func stereoRamp<U>(withInitialValue initialValue: inout Float,
multiplyingBy multiplierOne: U, _ multiplierTwo: U,
increment: Float) -> (firstOutput:[Float], secondOutput: [Float])
where
U: AccelerateBuffer,
U.Element == Float {
let n = multiplierOne.count
var firstOutput: Array<Float>!
let secondOutput = Array<Float>(unsafeUninitializedCapacity: n) {
secondBuffer, secondInitializedCount in
firstOutput = Array<Float>(unsafeUninitializedCapacity: n) {
firstBuffer, firstInitializedCount in
formStereoRamp(withInitialValue: &initialValue,
multiplyingBy: multiplierOne, multiplierTwo,
increment: increment,
results: &firstBuffer, &secondBuffer)
firstInitializedCount = n
}
secondInitializedCount = n
}
return (firstOutput: firstOutput,
secondOutput: secondOutput)
}
/// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, stereo, single-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplierOne: Input values multiplied by the ramp function.
/// - Parameter multiplierTwo: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter resultOne: Output values.
/// - Parameter resultTwo: Output values.
@inlinable
public static func formStereoRamp<U,V>(withInitialValue initialValue: inout Float,
multiplyingBy multiplierOne: U, _ multiplierTwo: U,
increment: Float,
results resultOne: inout V, _ resultTwo: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(multiplierOne.count == multiplierTwo.count)
precondition(resultOne.count == resultTwo.count)
precondition(multiplierOne.count == resultOne.count)
let n = vDSP_Length(resultTwo.count)
resultOne.withUnsafeMutableBufferPointer { o0 in
resultTwo.withUnsafeMutableBufferPointer { o1 in
multiplierOne.withUnsafeBufferPointer { i0 in
multiplierTwo.withUnsafeBufferPointer { i1 in
withUnsafePointer(to: increment) { step in
vDSP_vrampmul2(i0.baseAddress!,
i1.baseAddress!, 1,
&initialValue,
step,
o0.baseAddress!,
o1.baseAddress!, 1,
n)
}
}
}
}
}
}
/// Returns two arraya containing monotonically monotonically incrementing or decrementing values, multiplying by a source vector, stereo, double-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplierOne: Input values multiplied by the ramp function.
/// - Parameter multiplierTwo: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Returns: A tuple of two arrays containing the specified ramps.
@inlinable
public static func stereoRamp<U>(withInitialValue initialValue: inout Double,
multiplyingBy multiplierOne: U, _ multiplierTwo: U,
increment: Double) -> (firstOutput:[Double], secondOutput: [Double])
where
U: AccelerateBuffer,
U.Element == Double {
let n = multiplierOne.count
var firstOutput: Array<Double>!
let secondOutput = Array<Double>(unsafeUninitializedCapacity: n) {
secondBuffer, secondInitializedCount in
firstOutput = Array<Double>(unsafeUninitializedCapacity: n) {
firstBuffer, firstInitializedCount in
formStereoRamp(withInitialValue: &initialValue,
multiplyingBy: multiplierOne, multiplierTwo,
increment: increment,
results: &firstBuffer, &secondBuffer)
firstInitializedCount = n
}
secondInitializedCount = n
}
return (firstOutput: firstOutput,
secondOutput: secondOutput)
}
/// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, stereo, double-precision.
///
/// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly.
/// - Parameter multiplierOne: Input values multiplied by the ramp function.
/// - Parameter multiplierTwo: Input values multiplied by the ramp function.
/// - Parameter increment: The increment (or decrement if negative) between consecutive elements.
/// - Parameter resultOne: Output values.
/// - Parameter resultTwo: Output values.
@inlinable
public static func formStereoRamp<U,V>(withInitialValue initialValue: inout Double,
multiplyingBy multiplierOne: U, _ multiplierTwo: U,
increment: Double,
results resultOne: inout V, _ resultTwo: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(multiplierOne.count == multiplierTwo.count)
precondition(resultOne.count == resultTwo.count)
precondition(multiplierOne.count == resultOne.count)
let n = vDSP_Length(resultTwo.count)
resultOne.withUnsafeMutableBufferPointer { o0 in
resultTwo.withUnsafeMutableBufferPointer { o1 in
multiplierOne.withUnsafeBufferPointer { i0 in
multiplierTwo.withUnsafeBufferPointer { i1 in
withUnsafePointer(to: increment) { step in
vDSP_vrampmul2D(i0.baseAddress!,
i1.baseAddress!, 1,
&initialValue,
step,
o0.baseAddress!,
o1.baseAddress!, 1,
n)
}
}
}
}
}
}
}
| a89e4b5df39eabd17d539124d2a5d7b4 | 42.712925 | 188 | 0.510847 | false | false | false | false |
urdnot-ios/ShepardAppearanceConverter | refs/heads/master | ShepardAppearanceConverter/ShepardAppearanceConverter/Models/CoreData/CoreGameShepards.swift | mit | 1 | //
// GameShepards.swift
// ShepardAppearanceConverter
//
// Created by Emily Ivie on 8/31/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
extension Shepard: CoreDataDatedStorable {
public static var coreDataEntityName: String { return "GameShepards" }
// var createdDate: NSDate { get }
// var modifiedDate: NSDate { get set }
public func setAdditionalColumns(coreItem: NSManagedObject) {
coreItem.setValue(sequenceUuid, forKey: "sequenceUuid")
coreItem.setValue(uuid, forKey: "uuid")
}
public func setIdentifyingPredicate(fetchRequest: NSFetchRequest) {
fetchRequest.predicate = NSPredicate(format: "uuid = %@", uuid)
}
public mutating func save() -> Bool {
if hasSequenceChanges {
saveCommonDataToAllShepardsInSequence()
}
let isSaved = CoreDataManager.save(self)
if isSaved {
hasUnsavedChanges = false
}
return isSaved
}
public mutating func saveAnyChanges() -> Bool {
if hasUnsavedChanges {
return save()
}
return true
}
public mutating func saveCommonDataToAllShepardsInSequence() {
let shepards = Shepard.getAll(matching: [(key: "sequenceUuid", value: sequenceUuid)])
let commonData = getData()
var isSaved = true
for var sequenceShepard in shepards {
if sequenceShepard.uuid != uuid {
sequenceShepard.setCommonData(commonData)
sequenceShepard.hasSequenceChanges = false // don't recurse forever
isSaved = isSaved && sequenceShepard.saveAnyChanges()
}
}
hasSequenceChanges = !isSaved
}
public mutating func delete() -> Bool {
// if self == CurrentGame.shepard {
// // pick the most recent game instead (we always need a current shepard):
// let newShepard = SavedGames.shepardsSequences.sort{ $0.sortDate.compare($1.sortDate) == .OrderedDescending }.first?.lastPlayed ?? Shepard()
// CurrentGame.changeShepard(newShepard)
// }
let isDeleted = CoreDataManager.delete(self)
return isDeleted
}
public static func delete(uuid uuid: String) -> Bool {
return CoreDataManager.delete(matching: [(key: "uuid", value: uuid)], itemType: Shepard.self)
}
public static func get(uuid uuid: String) -> Shepard? {
return get(matching: [(key: "uuid", value: uuid)])
}
public static func get(matching criteria: [MatchingCriteria]) -> Shepard? {
let shepard: Shepard? = CoreDataManager.get(matching: criteria)
return shepard
}
public static func getAll() -> [Shepard] {
let shepards: [Shepard] = CoreDataManager.getAll()
return shepards
}
public static func getAll(matching criteria: [MatchingCriteria]) -> [Shepard] {
let shepards: [Shepard] = CoreDataManager.getAll(matching: criteria)
return shepards
}
public static func getCurrent() -> Shepard? {
let shepard: Shepard? = CoreDataManager.get(matching: [(key: "isCurrent", value: true)])
return shepard
}
} | 8c9dd640c25bba670649ab135e2f8116 | 32.680412 | 153 | 0.627373 | false | false | false | false |
lluisgerard/UIImageSwiftExtensions | refs/heads/master | UIImage+Resize.swift | mit | 1 | //
// UIImage+Resize.swift
//
// Created by Trevor Harmon on 08/05/09.
// Swift port by Giacomo Boccardo on 03/18/15.
//
// Free for personal or commercial use, with or without modification
// No warranty is expressed or implied.
//
public extension UIImage {
// Returns a copy of this image that is cropped to the given bounds.
// The bounds will be adjusted using CGRectIntegral.
// This method ignores the image's imageOrientation setting.
public func croppedImage(bounds: CGRect) -> UIImage {
let imageRef: CGImageRef = CGImageCreateWithImageInRect(self.CGImage, bounds)
return UIImage(CGImage: imageRef)!
}
public func thumbnailImage(thumbnailSize: Int, transparentBorder borderSize:Int, cornerRadius:Int, interpolationQuality quality:CGInterpolationQuality) -> UIImage {
var resizedImage = self.resizedImageWithContentMode(.ScaleAspectFill, bounds: CGSizeMake(CGFloat(thumbnailSize), CGFloat(thumbnailSize)), interpolationQuality: quality)
// Crop out any part of the image that's larger than the thumbnail size
// The cropped rect must be centered on the resized image
// Round the origin points so that the size isn't altered when CGRectIntegral is later invoked
let cropRect = CGRectMake(
round((resizedImage.size.width - CGFloat(thumbnailSize))/2),
round((resizedImage.size.height - CGFloat(thumbnailSize))/2),
CGFloat(thumbnailSize),
CGFloat(thumbnailSize)
)
let croppedImage = resizedImage.croppedImage(cropRect)
let transparentBorderImage = borderSize != 0 ? croppedImage.transparentBorderImage(borderSize) : croppedImage
return transparentBorderImage.roundedCornerImage(cornerSize: cornerRadius, borderSize: borderSize)
}
// Returns a rescaled copy of the image, taking into account its orientation
// The image will be scaled disproportionately if necessary to fit the bounds specified by the parameter
public func resizedImage(newSize: CGSize, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
var drawTransposed: Bool
switch(self.imageOrientation) {
case .Left, .LeftMirrored, .Right, .RightMirrored:
drawTransposed = true
default:
drawTransposed = false
}
return self.resizedImage(
newSize,
transform: self.transformForOrientation(newSize),
drawTransposed: drawTransposed,
interpolationQuality: quality
)
}
public func resizedImageWithContentMode(contentMode: UIViewContentMode, bounds: CGSize, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
let horizontalRatio = bounds.width / self.size.width
let verticalRatio = bounds.height / self.size.height
var ratio: CGFloat = 1
switch(contentMode) {
case .ScaleAspectFill:
ratio = max(horizontalRatio, verticalRatio)
case .ScaleAspectFit:
ratio = min(horizontalRatio, verticalRatio)
default:
fatalError("Unsupported content mode \(contentMode)")
}
let newSize: CGSize = CGSizeMake(self.size.width * ratio, self.size.height * ratio)
return self.resizedImage(newSize, interpolationQuality: quality)
}
private func normalizeBitmapInfo(bI: CGBitmapInfo) -> CGBitmapInfo {
var alphaInfo: CGBitmapInfo = bI & CGBitmapInfo.AlphaInfoMask
if alphaInfo == CGBitmapInfo(CGImageAlphaInfo.Last.rawValue) {
alphaInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
}
if alphaInfo == CGBitmapInfo(CGImageAlphaInfo.First.rawValue) {
alphaInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.rawValue)
}
var newBI: CGBitmapInfo = bI & ~CGBitmapInfo.AlphaInfoMask;
newBI |= alphaInfo;
return newBI
}
private func resizedImage(newSize: CGSize, transform: CGAffineTransform, drawTransposed transpose: Bool, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
let newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height))
let transposedRect = CGRectMake(0, 0, newRect.size.height, newRect.size.width)
let imageRef: CGImageRef = self.CGImage
// Build a context that's the same dimensions as the new size
let imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef))
var colorspaceRef = CGImageGetColorSpace(imageRef)
let unsupportedColorSpace = (imageColorSpaceModel.value == 0 || imageColorSpaceModel.value == -1 || imageColorSpaceModel.value == kCGColorSpaceModelIndexed.value)
if unsupportedColorSpace {
println("Unsupported Color Space")
colorspaceRef = CGColorSpaceCreateDeviceRGB()
}
let bitmapInfo = CGBitmapInfo(CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue)
let bitmap : CGContextRef = CGBitmapContextCreate(
nil,
Int(newRect.size.width),
Int(newRect.size.height),
8, //CGImageGetBitsPerComponent(imageRef),
0,
colorspaceRef,
bitmapInfo
)
// Rotate and/or flip the image if required by its orientation
CGContextConcatCTM(bitmap, transform)
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(bitmap, quality)
// Draw into the context; this scales the image
CGContextDrawImage(bitmap, transpose ? transposedRect: newRect, imageRef)
// Get the resized image from the context and a UIImage
let newImageRef: CGImageRef = CGBitmapContextCreateImage(bitmap)
return UIImage(CGImage: newImageRef)!
}
private func transformForOrientation(newSize: CGSize) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransformIdentity
switch (self.imageOrientation) {
case .Down, .DownMirrored:
// EXIF = 3 / 4
transform = CGAffineTransformTranslate(transform, newSize.width, newSize.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
case .Left, .LeftMirrored:
// EXIF = 6 / 5
transform = CGAffineTransformTranslate(transform, newSize.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case .Right, .RightMirrored:
// EXIF = 8 / 7
transform = CGAffineTransformTranslate(transform, 0, newSize.height)
transform = CGAffineTransformRotate(transform, -CGFloat(M_PI_2))
default:
break
}
switch(self.imageOrientation) {
case .UpMirrored, .DownMirrored:
// EXIF = 2 / 4
transform = CGAffineTransformTranslate(transform, newSize.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
// EXIF = 5 / 7
transform = CGAffineTransformTranslate(transform, newSize.height, 0)
transform = CGAffineTransformScale(transform, -1, 1)
default:
break
}
return transform
}
}
| 6544427f589d807596e9441a8ebc54b3 | 43.364706 | 176 | 0.656855 | false | false | false | false |
iAugux/Zoom-Contacts | refs/heads/master | Phonetic/Extensions/UIView+Extension.swift | mit | 1 | //
// UIView+Extension.swift
//
// Created by Augus on 9/4/15.
// Copyright © 2015 iAugus. All rights reserved.
//
import UIKit
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.nextResponder()
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
extension UIView {
func setFrameSize(size: CGSize) {
var frame = self.frame
frame.size = size
self.frame = frame
}
func setFrameHeight(height: CGFloat) {
var frame = self.frame
frame.size.height = height
self.frame = frame
}
func setFrameWidth(width: CGFloat) {
var frame = self.frame
frame.size.width = width
self.frame = frame
}
func setFrameOriginX(originX: CGFloat) {
var frame = self.frame
frame.origin.x = originX
self.frame = frame
}
func setFrameOriginY(originY: CGFloat) {
var frame = self.frame
frame.origin.y = originY
self.frame = frame
}
/**
set current view's absolute center to other view's center
- parameter view: other view
*/
func centerTo(view view: UIView) {
self.frame.origin.x = view.bounds.midX - self.frame.width / 2
self.frame.origin.y = view.bounds.midY - self.frame.height / 2
}
}
extension UIView {
func simulateHighlight() {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.alpha = 0.5
}, completion: { (_) -> Void in
UIView.animateWithDuration(0.1, delay: 0.1, options: .CurveEaseInOut, animations: { () -> Void in
self.alpha = 1
}, completion: nil)
})
}
}
extension UIView {
func isPointInside(fromView: UIView, point: CGPoint, event: UIEvent?) -> Bool {
return pointInside(fromView.convertPoint(point, toView: self), withEvent: event)
}
}
// MARK: - rotation animation
extension UIView {
/**
Angle: 𝞹
- parameter duration: <#duration description#>
- parameter beginWithClockwise: <#beginWithClockwise description#>
- parameter clockwise: <#clockwise description#>
- parameter animated: <#animated description#>
*/
func rotationAnimation(duration: CFTimeInterval? = 0.4, beginWithClockwise: Bool, clockwise: Bool, animated: Bool) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
let angle: Double = beginWithClockwise ? (clockwise ? M_PI : 0) : (clockwise ? 0 : -M_PI)
if beginWithClockwise {
if !clockwise { rotationAnimation.fromValue = M_PI }
} else {
if clockwise { rotationAnimation.fromValue = -M_PI }
}
rotationAnimation.toValue = angle
rotationAnimation.duration = animated ? duration! : 0
rotationAnimation.repeatCount = 0
rotationAnimation.delegate = self
rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
rotationAnimation.fillMode = kCAFillModeForwards
rotationAnimation.removedOnCompletion = false
layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
}
/**
Angle: 𝞹/2
- parameter duration: <#duration description#>
- parameter clockwise: <#clockwise description#>
- parameter animated: <#animated description#>
*/
func rotationAnimation(duration: NSTimeInterval, clockwise: Bool, animated: Bool) {
let angle = CGFloat(clockwise ? M_PI_2 : -M_PI_2)
if animated {
UIView.animateWithDuration(duration, delay: 0, options: .CurveLinear, animations: { () -> Void in
self.transform = CGAffineTransformRotate(self.transform, angle)
}, completion: nil)
} else {
self.transform = CGAffineTransformRotate(self.transform, angle)
}
}
}
// MARK: - Twinkle
extension UIView {
func twinkling(duration: NSTimeInterval, minAlpha: CGFloat = 0, maxAlpha: CGFloat = 1) {
UIView.animateWithDuration(duration, animations: {
self.alpha = minAlpha
}) { (finished) in
if finished {
UIView.animateWithDuration(duration, animations: {
self.alpha = maxAlpha
}, completion: { (finished) in
if finished {
self.twinkling(duration, minAlpha: minAlpha, maxAlpha: maxAlpha)
}
})
}
}
}
}
| 3aba83028e687262babfbe5327acda6e | 28.145349 | 120 | 0.574307 | false | false | false | false |
aleksandrshoshiashvili/AwesomeSpotlightView | refs/heads/master | AwesomeSpotlightViewDemoObjC/Pods/AwesomeSpotlightView/AwesomeSpotlightView/Classes/AwesomeSpotlightView.swift | mit | 1 | //
// AwesomeSpotlightView.swift
// AwesomeSpotlightView
//
// Created by Alex Shoshiashvili on 24.02.17.
// Copyright © 2017 Alex Shoshiashvili. All rights reserved.
//
import UIKit
// MARK: - AwesomeSpotlightViewDelegate
@objc public protocol AwesomeSpotlightViewDelegate {
@objc optional func spotlightView(_ spotlightView: AwesomeSpotlightView, willNavigateToIndex index: Int)
@objc optional func spotlightView(_ spotlightView: AwesomeSpotlightView, didNavigateToIndex index: Int)
@objc optional func spotlightViewWillCleanup(_ spotlightView: AwesomeSpotlightView, atIndex index: Int)
@objc optional func spotlightViewDidCleanup(_ spotlightView: AwesomeSpotlightView)
}
@objcMembers
public class AwesomeSpotlightView: UIView {
public var delegate: AwesomeSpotlightViewDelegate?
// MARK: - private variables
private static let kAnimationDuration = 0.3
private static let kCutoutRadius: CGFloat = 4.0
private static let kMaxLabelWidth = 280.0
private static let kMaxLabelSpacing: CGFloat = 35.0
private static let kEnableContinueLabel = false
private static let kEnableSkipButton = false
private static let kEnableArrowDown = false
private static let kShowAllSpotlightsAtOnce = false
private static let kTextLabelFont = UIFont.systemFont(ofSize: 20.0)
private static let kContinueLabelFont = UIFont.systemFont(ofSize: 13.0)
private static let kSkipButtonFont = UIFont.boldSystemFont(ofSize: 13.0)
private static let kSkipButtonLastStepTitle = "Done".localized
private var spotlightMask = CAShapeLayer()
private var arrowDownImageView = UIImageView()
private var arrowDownSize = CGSize(width: 12, height: 18)
private var delayTime: TimeInterval = 0.35
private var hitTestPoints: [CGPoint] = []
// MARK: - public variables
public var spotlightsArray: [AwesomeSpotlight] = []
public var textLabel = UILabel()
public var continueLabel = UILabel()
public var skipSpotlightButton = UIButton()
public var animationDuration = kAnimationDuration
public var cutoutRadius: CGFloat = kCutoutRadius
public var maxLabelWidth = kMaxLabelWidth
public var labelSpacing: CGFloat = kMaxLabelSpacing
public var enableArrowDown = kEnableArrowDown
public var showAllSpotlightsAtOnce = kShowAllSpotlightsAtOnce
public var continueButtonModel = AwesomeTabButton(title: "Continue".localized, font: kContinueLabelFont, isEnable: kEnableContinueLabel)
public var skipButtonModel = AwesomeTabButton(title: "Skip".localized, font: kSkipButtonFont, isEnable: kEnableSkipButton)
public var skipButtonLastStepTitle = kSkipButtonLastStepTitle
public var spotlightMaskColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.6) {
didSet {
spotlightMask.fillColor = spotlightMaskColor.cgColor
}
}
public var textLabelFont = kTextLabelFont {
didSet {
textLabel.font = textLabelFont
}
}
public var isShowed: Bool {
return currentIndex != 0
}
public var currentIndex = 0
// MARK: - Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
}
convenience public init(frame: CGRect, spotlight: [AwesomeSpotlight]) {
self.init(frame: frame)
self.spotlightsArray = spotlight
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup
private func setup() {
setupMask()
setupTouches()
setupTextLabel()
setupArrowDown()
isHidden = true
}
private func setupMask() {
spotlightMask.fillRule = CAShapeLayerFillRule.evenOdd
spotlightMask.fillColor = spotlightMaskColor.cgColor
layer.addSublayer(spotlightMask)
}
private func setupTouches() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AwesomeSpotlightView.userDidTap(_:)))
addGestureRecognizer(tapGestureRecognizer)
}
private func setupTextLabel() {
let textLabelRect = CGRect(x: 0, y: 0, width: maxLabelWidth, height: 0)
textLabel = UILabel(frame: textLabelRect)
textLabel.backgroundColor = .clear
textLabel.textColor = .white
textLabel.font = textLabelFont
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
textLabel.textAlignment = .center
textLabel.alpha = 0
addSubview(textLabel)
}
private func setupArrowDown() {
let arrowDownIconName = "arrowDownIcon"
if let bundlePath = Bundle.main.path(forResource: "AwesomeSpotlightViewBundle", ofType: "bundle") {
if let _ = Bundle(path: bundlePath)?.path(forResource: arrowDownIconName, ofType: "png") {
let arrowDownImage = UIImage(named: arrowDownIconName, in: Bundle(path: bundlePath), compatibleWith: nil)
arrowDownImageView = UIImageView(image: arrowDownImage)
arrowDownImageView.alpha = 0
addSubview(arrowDownImageView)
}
}
}
private func setupContinueLabel() {
let continueLabelWidth = skipButtonModel.isEnable ? 0.7 * bounds.size.width : bounds.size.width
let continueLabelHeight: CGFloat = 30.0
if #available(iOS 11.0, *) {
continueLabel = UILabel(frame: CGRect(x: 0, y: bounds.size.height - continueLabelHeight - safeAreaInsets.bottom, width: continueLabelWidth, height: continueLabelHeight))
} else {
continueLabel = UILabel(frame: CGRect(x: 0, y: bounds.size.height - continueLabelHeight, width: continueLabelWidth, height: continueLabelHeight))
}
continueLabel.font = continueButtonModel.font
continueLabel.textAlignment = .center
continueLabel.text = continueButtonModel.title
continueLabel.alpha = 0
continueLabel.backgroundColor = continueButtonModel.backgroundColor ?? .white
addSubview(continueLabel)
}
private func setupSkipSpotlightButton() {
let continueLabelWidth = 0.7 * bounds.size.width
let skipSpotlightButtonWidth = bounds.size.width - continueLabelWidth
let skipSpotlightButtonHeight: CGFloat = 30.0
if #available(iOS 11.0, *) {
skipSpotlightButton = UIButton(frame: CGRect(x: continueLabelWidth, y: bounds.size.height - skipSpotlightButtonHeight - safeAreaInsets.bottom, width: skipSpotlightButtonWidth, height: skipSpotlightButtonHeight))
} else {
skipSpotlightButton = UIButton(frame: CGRect(x: continueLabelWidth, y: bounds.size.height - skipSpotlightButtonHeight, width: skipSpotlightButtonWidth, height: skipSpotlightButtonHeight))
}
skipSpotlightButton.addTarget(self, action: #selector(AwesomeSpotlightView.skipSpotlight), for: .touchUpInside)
skipSpotlightButton.setTitle(skipButtonModel.title, for: [])
skipSpotlightButton.titleLabel?.font = skipButtonModel.font
skipSpotlightButton.alpha = 0
skipSpotlightButton.tintColor = .white
skipSpotlightButton.backgroundColor = skipButtonModel.backgroundColor ?? .clear
addSubview(skipSpotlightButton)
}
// MARK: - Touches
@objc func userDidTap(_ recognizer: UITapGestureRecognizer) {
goToSpotlightAtIndex(index: currentIndex + 1)
}
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
let localPoint = convert(point, from: self)
hitTestPoints.append(localPoint)
guard currentIndex < spotlightsArray.count else {
return view
}
let currentSpotlight = spotlightsArray[currentIndex]
if currentSpotlight.rect.contains(localPoint), currentSpotlight.isAllowPassTouchesThroughSpotlight {
if hitTestPoints.filter({ $0 == localPoint }).count == 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: {
self.cleanup()
})
}
return nil
}
return view
}
// MARK: - Presenter
public func start() {
alpha = 0
isHidden = false
textLabel.font = textLabelFont
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 1
}) { (finished) in
self.goToFirstSpotlight()
}
}
private func goToFirstSpotlight() {
goToSpotlightAtIndex(index: 0)
}
private func goToSpotlightAtIndex(index: Int) {
if index >= spotlightsArray.count {
cleanup()
} else if showAllSpotlightsAtOnce {
showSpotlightsAllAtOnce()
} else {
showSpotlightAtIndex(index: index)
}
}
private func showSpotlightsAllAtOnce() {
if let firstSpotlight = spotlightsArray.first {
continueButtonModel.isEnable = false
skipButtonModel.isEnable = false
setCutoutToSpotlight(spotlight: firstSpotlight)
animateCutoutToSpotlights(spotlights: spotlightsArray)
currentIndex = spotlightsArray.count
}
}
private func showSpotlightAtIndex(index: Int) {
currentIndex = index
let currentSpotlight = spotlightsArray[index]
delegate?.spotlightView?(self, willNavigateToIndex: index)
showTextLabel(spotlight: currentSpotlight)
showArrowIfNeeded(spotlight: currentSpotlight)
if currentIndex == 0 {
setCutoutToSpotlight(spotlight: currentSpotlight)
}
animateCutoutToSpotlight(spotlight: currentSpotlight)
showContinueLabelIfNeeded(index: index)
showSkipButtonIfNeeded(index: index)
}
private func showArrowIfNeeded(spotlight: AwesomeSpotlight) {
if enableArrowDown {
arrowDownImageView.frame = CGRect(origin: CGPoint(x: center.x - 6, y: spotlight.rect.origin.y - 18 - 16), size: arrowDownSize)
UIView.animate(withDuration: animationDuration, animations: {
self.arrowDownImageView.alpha = 1
})
}
}
private func showTextLabel(spotlight: AwesomeSpotlight) {
textLabel.alpha = 0
calculateTextPositionAndSizeWithSpotlight(spotlight: spotlight)
UIView.animate(withDuration: animationDuration) {
self.textLabel.alpha = 1
}
}
private func showContinueLabelIfNeeded(index: Int) {
if continueButtonModel.isEnable {
if index == 0 {
setupContinueLabel()
UIView.animate(withDuration: animationDuration, delay: delayTime, options: .curveLinear, animations: {
self.continueLabel.alpha = 1
})
} else if index >= spotlightsArray.count - 1 && continueLabel.alpha != 0 {
continueLabel.alpha = 0
continueLabel.removeFromSuperview()
}
}
}
private func showSkipButtonIfNeeded(index: Int) {
if skipButtonModel.isEnable && index == 0 {
setupSkipSpotlightButton()
UIView.animate(withDuration: animationDuration, delay: delayTime, options: .curveLinear, animations: {
self.skipSpotlightButton.alpha = 1
})
} else if skipSpotlightButton.isEnabled && index == spotlightsArray.count - 1 {
skipSpotlightButton.setTitle(skipButtonLastStepTitle, for: .normal)
}
}
@objc func skipSpotlight() {
goToSpotlightAtIndex(index: spotlightsArray.count)
}
private func skipAllSpotlights() {
goToSpotlightAtIndex(index: spotlightsArray.count)
}
// MARK: Helper
private func calculateRectWithMarginForSpotlight(_ spotlight: AwesomeSpotlight) -> CGRect {
var rect = spotlight.rect
rect.size.width += spotlight.margin.left + spotlight.margin.right
rect.size.height += spotlight.margin.bottom + spotlight.margin.top
rect.origin.x = rect.origin.x - (spotlight.margin.left + spotlight.margin.right) / 2.0
rect.origin.y = rect.origin.y - (spotlight.margin.top + spotlight.margin.bottom) / 2.0
return rect
}
private func calculateTextPositionAndSizeWithSpotlight(spotlight: AwesomeSpotlight) {
textLabel.frame = CGRect(x: 0, y: 0, width: maxLabelWidth, height: 0)
textLabel.attributedText = spotlight.showedText
if enableArrowDown && currentIndex == 0 {
labelSpacing += 18
}
textLabel.sizeToFit()
let rect = calculateRectWithMarginForSpotlight(spotlight)
var y = rect.origin.y + rect.size.height + labelSpacing
let bottomY = y + textLabel.frame.size.height + labelSpacing
if bottomY > bounds.size.height {
y = rect.origin.y - labelSpacing - textLabel.frame.size.height
}
let x : CGFloat = CGFloat(floor(bounds.size.width - textLabel.frame.size.width) / 2.0)
textLabel.frame = CGRect(origin: CGPoint(x: x, y: y), size: textLabel.frame.size)
}
// MARK: - Cutout and Animate
private func cutoutToSpotlight(spotlight: AwesomeSpotlight, isFirst : Bool = false) -> UIBezierPath {
var rect = calculateRectWithMarginForSpotlight(spotlight)
if isFirst {
let x = floor(spotlight.rect.origin.x + (spotlight.rect.size.width / 2.0))
let y = floor(spotlight.rect.origin.y + (spotlight.rect.size.height / 2.0))
let center = CGPoint(x: x, y: y)
rect = CGRect(origin: center, size: CGSize.zero)
}
let spotlightPath = UIBezierPath(rect: bounds)
var cutoutPath = UIBezierPath()
switch spotlight.shape {
case .rectangle:
cutoutPath = UIBezierPath(rect: rect)
case .roundRectangle:
cutoutPath = UIBezierPath(roundedRect: rect, cornerRadius: cutoutRadius)
case .circle:
cutoutPath = UIBezierPath(ovalIn: rect)
}
spotlightPath.append(cutoutPath)
return spotlightPath
}
private func cutoutToSpotlightCGPath(spotlight: AwesomeSpotlight, isFirst : Bool = false) -> CGPath {
return cutoutToSpotlight(spotlight: spotlight, isFirst: isFirst).cgPath
}
private func setCutoutToSpotlight(spotlight: AwesomeSpotlight) {
spotlightMask.path = cutoutToSpotlightCGPath(spotlight: spotlight, isFirst: true)
}
private func animateCutoutToSpotlight(spotlight: AwesomeSpotlight) {
let path = cutoutToSpotlightCGPath(spotlight: spotlight)
animateCutoutWithPath(path: path)
}
private func animateCutoutToSpotlights(spotlights: [AwesomeSpotlight]) {
let spotlightPath = UIBezierPath(rect: bounds)
for spotlight in spotlights {
var cutoutPath = UIBezierPath()
switch spotlight.shape {
case .rectangle:
cutoutPath = UIBezierPath(rect: spotlight.rect)
case .roundRectangle:
cutoutPath = UIBezierPath(roundedRect: spotlight.rect, cornerRadius: cutoutRadius)
case .circle:
cutoutPath = UIBezierPath(ovalIn: spotlight.rect)
}
spotlightPath.append(cutoutPath)
}
animateCutoutWithPath(path: spotlightPath.cgPath)
}
private func animateCutoutWithPath(path: CGPath) {
let animationKeyPath = "path"
let animation = CABasicAnimation(keyPath: animationKeyPath)
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.duration = animationDuration
animation.isRemovedOnCompletion = false
animation.fillMode = CAMediaTimingFillMode.forwards
animation.fromValue = spotlightMask.path
animation.toValue = path
spotlightMask.add(animation, forKey: animationKeyPath)
spotlightMask.path = path
}
// MARK: - Cleanup
private func cleanup() {
delegate?.spotlightViewWillCleanup?(self, atIndex: currentIndex)
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 0
}) { (finished) in
if finished {
self.removeFromSuperview()
self.currentIndex = 0
self.textLabel.alpha = 0
self.continueLabel.alpha = 0
self.skipSpotlightButton.alpha = 0
self.hitTestPoints = []
self.delegate?.spotlightViewDidCleanup?(self)
}
}
}
// MARK: - Objective-C Support Function
// Objective-C provides support function because it does not correspond to struct
public func setContinueButtonEnable(_ isEnable:Bool) {
self.continueButtonModel.isEnable = isEnable
}
public func setSkipButtonEnable(_ isEnable:Bool) {
self.skipButtonModel.isEnable = isEnable
}
}
extension AwesomeSpotlightView: CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
delegate?.spotlightView?(self, didNavigateToIndex: currentIndex)
}
}
| 167649004a70aa99a26652f25147dcfd | 37.409091 | 223 | 0.650268 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/Sema/availability_versions.swift | apache-2.0 | 2 | // RUN: %target-parse-verify-swift -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module
// RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -parse %s 2>&1 | FileCheck %s '--implicit-check-not=<unknown>:0'
// Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed
// RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -parse -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:'
// REQUIRES: OS=macosx
func markUsed<T>(_ t: T) {}
@available(OSX, introduced: 10.9)
func globalFuncAvailableOn10_9() -> Int { return 9 }
@available(OSX, introduced: 10.51)
func globalFuncAvailableOn10_51() -> Int { return 10 }
@available(OSX, introduced: 10.52)
func globalFuncAvailableOn10_52() -> Int { return 11 }
// Top level should reflect the minimum deployment target.
let ignored1: Int = globalFuncAvailableOn10_9()
let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Functions without annotations should reflect the minimum deployment target.
func functionWithoutAvailability() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Functions with annotations should refine their bodies.
@available(OSX, introduced: 10.51)
func functionAvailableOn10_51() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
// Nested functions should get their own refinement context.
@available(OSX, introduced: 10.52)
func innerFunctionAvailableOn10_52() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52()
}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Don't allow script-mode globals to marked potentially unavailable. Their
// initializers are eagerly executed.
@available(OSX, introduced: 10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}}
var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51()
// Still allow other availability annotations on script-mode globals
@available(OSX, deprecated: 10.51)
var deprecatedGlobalInScriptMode: Int = 5
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
} else {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
@available(iOS, introduced: 8.0)
func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 }
if #available(OSX 10.51, iOS 8.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0()
}
if #available(iOS 9.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Multiple unavailable references in a single statement
let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
globalFuncAvailableOn10_9()
let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Overloaded global functions
@available(OSX, introduced: 10.9)
func overloadedFunction() {}
@available(OSX, introduced: 10.51)
func overloadedFunction(_ on1010: Int) {}
overloadedFunction()
overloadedFunction(0) // expected-error {{'overloadedFunction' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Unavailable methods
class ClassWithUnavailableMethod {
@available(OSX, introduced: 10.9)
func methAvailableOn10_9() {}
@available(OSX, introduced: 10.51)
func methAvailableOn10_51() {}
@available(OSX, introduced: 10.51)
class func classMethAvailableOn10_51() {}
func someOtherMethod() {
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
func callUnavailableMethods(_ o: ClassWithUnavailableMethod) {
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func callUnavailableMethodsViaIUO(_ o: ClassWithUnavailableMethod!) {
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func callUnavailableClassMethod() {
ClassWithUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let m10_51 = ClassWithUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
}
class SubClassWithUnavailableMethod : ClassWithUnavailableMethod {
func someMethod() {
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
class SubClassOverridingUnavailableMethod : ClassWithUnavailableMethod {
override func methAvailableOn10_51() {
methAvailableOn10_9()
super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
let m10_9 = super.methAvailableOn10_9
m10_9()
let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
m10_51()
}
func someMethod() {
methAvailableOn10_9()
// Calling our override should be fine
methAvailableOn10_51()
}
}
class ClassWithUnavailableOverloadedMethod {
@available(OSX, introduced: 10.9)
func overloadedMethod() {}
@available(OSX, introduced: 10.51)
func overloadedMethod(_ on1010: Int) {}
}
func callUnavailableOverloadedMethod(_ o: ClassWithUnavailableOverloadedMethod) {
o.overloadedMethod()
o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Initializers
class ClassWithUnavailableInitializer {
@available(OSX, introduced: 10.9)
required init() { }
@available(OSX, introduced: 10.51)
required init(_ val: Int) { }
convenience init(s: String) {
self.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing initializer}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
convenience init(onlyOn1010: String) {
self.init(5)
}
}
func callUnavailableInitializer() {
_ = ClassWithUnavailableInitializer()
_ = ClassWithUnavailableInitializer(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let i = ClassWithUnavailableInitializer.self
_ = i.init()
_ = i.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
class SuperWithWithUnavailableInitializer {
@available(OSX, introduced: 10.9)
init() { }
@available(OSX, introduced: 10.51)
init(_ val: Int) { }
}
class SubOfClassWithUnavailableInitializer : SuperWithWithUnavailableInitializer {
override init(_ val: Int) {
super.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing initializer}}
// expected-note@-3 {{add 'if #available' version check}}
}
override init() {
super.init()
}
@available(OSX, introduced: 10.51)
init(on1010: Int) {
super.init(22)
}
}
// Properties
class ClassWithUnavailableProperties {
@available(OSX, introduced: 10.9) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
var nonLazyAvailableOn10_9Stored: Int = 9
@available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
var nonLazyAvailableOn10_51Stored : Int = 10
@available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
let nonLazyLetAvailableOn10_51Stored : Int = 10
// Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable.
// We don't support potentially unavailable stored properties yet.
var storedPropertyOfUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.9)
lazy var availableOn10_9Stored: Int = 9
@available(OSX, introduced: 10.51)
lazy var availableOn10_51Stored : Int = 10
@available(OSX, introduced: 10.9)
var availableOn10_9Computed: Int {
get {
let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: Int = availableOn10_51Stored
}
return availableOn10_9Stored
}
set(newVal) {
availableOn10_9Stored = newVal
}
}
@available(OSX, introduced: 10.51)
var availableOn10_51Computed: Int {
get {
return availableOn10_51Stored
}
set(newVal) {
availableOn10_51Stored = newVal
}
}
var propWithSetterOnlyAvailableOn10_51 : Int {
get {
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing var}}
// expected-note@-3 {{add 'if #available' version check}}
return 0
}
@available(OSX, introduced: 10.51)
set(newVal) {
globalFuncAvailableOn10_51()
}
}
var propWithGetterOnlyAvailableOn10_51 : Int {
@available(OSX, introduced: 10.51)
get {
globalFuncAvailableOn10_51()
return 0
}
set(newVal) {
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing var}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
var propWithGetterAndSetterOnlyAvailableOn10_51 : Int {
@available(OSX, introduced: 10.51)
get {
return 0
}
@available(OSX, introduced: 10.51)
set(newVal) {
}
}
var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties {
get {
return ClassWithUnavailableProperties()
}
@available(OSX, introduced: 10.51)
set(newVal) {
}
}
var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties {
@available(OSX, introduced: 10.51)
get {
return ClassWithUnavailableProperties()
}
set(newVal) {
}
}
}
@available(OSX, introduced: 10.51)
class ClassWithReferencesInInitializers {
var propWithInitializer10_51: Int = globalFuncAvailableOn10_51()
var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51()
lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing var}}
}
func accessUnavailableProperties(_ o: ClassWithUnavailableProperties) {
// Stored properties
let _: Int = o.availableOn10_9Stored
let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.availableOn10_9Stored = 9
o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Computed Properties
let _: Int = o.availableOn10_9Computed
let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.availableOn10_9Computed = 9
o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Getter allowed on 10.9 but setter is not
let _: Int = o.propWithSetterOnlyAvailableOn10_51
o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Setter is allowed on 10.51 and greater
o.propWithSetterOnlyAvailableOn10_51 = 5
}
// Setter allowed on 10.9 but getter is not
o.propWithGetterOnlyAvailableOn10_51 = 5
let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Getter is allowed on 10.51 and greater
let _: Int = o.propWithGetterOnlyAvailableOn10_51
}
// Tests for nested member refs
// Both getters are potentially unavailable.
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
// Nested getter is potentially unavailable, outer getter is available
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Nested getter is available, outer getter is potentially unavailable
let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Both getters are always available.
let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51
// Nesting in source of assignment
var v: Int
v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Inout requires access to both getter and setter
func takesInout(_ i : inout Int) { }
takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
takesInout(&o.availableOn10_9Computed)
takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// _silgen_name
@_silgen_name("SomeName")
@available(OSX, introduced: 10.51)
func funcWith_silgen_nameAvailableOn10_51(_ p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51
// Enums
@available(OSX, introduced: 10.51)
enum EnumIntroducedOn10_51 {
case Element
}
@available(OSX, introduced: 10.52)
enum EnumIntroducedOn10_52 {
case Element
}
@available(OSX, introduced: 10.51)
enum CompassPoint {
case North
case South
case East
@available(OSX, introduced: 10.52)
case West
case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51)
@available(OSX, introduced: 10.52)
case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52)
@available(OSX, introduced: 10.52)
case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52)
case WithUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing case}}
case WithUnavailablePayload1(p : EnumIntroducedOn10_52), WithUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing case}}
}
@available(OSX, introduced: 10.52)
func functionTakingEnumIntroducedOn10_52(_ e: EnumIntroducedOn10_52) { }
func useEnums() {
let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: CompassPoint = .North
let _: CompassPoint = .West // expected-error {{'West' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
if #available(OSX 10.52, *) {
let _: CompassPoint = .West
}
// Pattern matching on an enum element does not require it to be definitely available
if #available(OSX 10.51, *) {
let point: CompassPoint = .North
switch (point) {
case .North, .South, .East:
markUsed("NSE")
case .West: // We do not expect an error here
markUsed("W")
case .WithAvailableByEnumElementPayload(let p):
markUsed("WithAvailableByEnumElementPayload")
// For the moment, we do not incorporate enum element availability into
// TRC construction. Perhaps we should?
functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
}
}
// Classes
@available(OSX, introduced: 10.9)
class ClassAvailableOn10_9 {
func someMethod() {}
class func someClassMethod() {}
var someProp : Int = 22
}
@available(OSX, introduced: 10.51)
class ClassAvailableOn10_51 { // expected-note {{enclosing scope here}}
func someMethod() {}
class func someClassMethod() {
let _ = ClassAvailableOn10_51()
}
var someProp : Int = 22
@available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}}
func someMethodAvailableOn10_9() { }
@available(OSX, introduced: 10.52)
var propWithGetter: Int { // expected-note{{enclosing scope here}}
@available(OSX, introduced: 10.51) // expected-error {{declaration cannot be more available than enclosing scope}}
get { return 0 }
}
}
func classAvailability() {
ClassAvailableOn10_9.someClassMethod()
ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
ClassAvailableOn10_9.self
ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let o10_9 = ClassAvailableOn10_9()
let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o10_9.someMethod()
o10_51.someMethod()
let _ = o10_9.someProp
let _ = o10_51.someProp
}
func castingUnavailableClass(_ o : AnyObject) {
let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
protocol Creatable {
init()
}
@available(OSX, introduced: 10.51)
class ClassAvailableOn10_51_Creatable : Creatable {
required init() {}
}
func create<T : Creatable>() -> T {
return T()
}
class ClassWithGenericTypeParameter<T> { }
class ClassWithTwoGenericTypeParameter<T, S> { }
func classViaTypeParameter() {
let _ : ClassAvailableOn10_51_Creatable = // expected-error {{'ClassAvailableOn10_51_Creatable' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
create()
let _ = create() as
ClassAvailableOn10_51_Creatable // expected-error {{'ClassAvailableOn10_51_Creatable' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Unavailable class used in declarations
class ClassWithDeclarationsOfUnavailableClasses {
@available(OSX, introduced: 10.51)
init() {
unavailablePropertyOfUnavailableType = ClassAvailableOn10_51()
unavailablePropertyOfUnavailableType = ClassAvailableOn10_51()
}
var propertyOfUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.51)
lazy var unavailablePropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced: 10.51)
lazy var unavailablePropertyOfOptionalUnavailableType: ClassAvailableOn10_51? = nil
@available(OSX, introduced: 10.51)
lazy var unavailablePropertyOfUnavailableTypeWithInitializer: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced: 10.51)
static var unavailableStaticPropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced: 10.51)
static var unavailableStaticPropertyOfOptionalUnavailableType: ClassAvailableOn10_51?
func methodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
}
@available(OSX, introduced: 10.51)
func unavailableMethodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) {
}
func methodWithUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
func unavailableMethodWithUnavailableReturnType() -> ClassAvailableOn10_51 {
return ClassAvailableOn10_51()
}
func methodWithUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
func unavailableMethodWithUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType()
}
}
func referToUnavailableStaticProperty() {
let _ = ClassWithDeclarationsOfUnavailableClasses.unavailableStaticPropertyOfUnavailableType // expected-error {{'unavailableStaticPropertyOfUnavailableType' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
class ClassExtendingUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
}
@available(OSX, introduced: 10.51)
class UnavailableClassExtendingUnavailableClass : ClassAvailableOn10_51 {
}
// Method availability is contravariant
class SuperWithAlwaysAvailableMembers {
func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}}
}
var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}}
get { return 9 }
set(newVal) {}
}
var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
set(newVal) {} // expected-note {{overridden declaration is here}}
}
var getterShouldAlwaysBeAvailableProperty: Int {
get { return 9 } // expected-note {{overridden declaration is here}}
set(newVal) {}
}
}
class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers {
@available(OSX, introduced: 10.51)
override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}}
}
@available(OSX, introduced: 10.51)
override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
get { return 10 }
set(newVal) {}
}
override var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
@available(OSX, introduced: 10.51)
set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
// This is a terrible diagnostic. rdar://problem/20427938
}
override var getterShouldAlwaysBeAvailableProperty: Int {
@available(OSX, introduced: 10.51)
get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
set(newVal) {}
}
}
class SuperWithLimitedMemberAvailability {
@available(OSX, introduced: 10.51)
func someMethod() {
}
@available(OSX, introduced: 10.51)
var someProperty: Int {
get { return 10 }
set(newVal) {}
}
}
class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability {
@available(OSX, introduced: 10.9)
override func someMethod() {
super.someMethod() // expected-error {{'someMethod()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
super.someMethod()
}
}
@available(OSX, introduced: 10.9)
override var someProperty: Int {
get {
let _ = super.someProperty // expected-error {{'someProperty' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _ = super.someProperty
}
return 9
}
set(newVal) {}
}
}
// Inheritance and availability
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_9 {
}
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.9)
protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 {
}
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
// We allow nominal types to conform to protocols that are less available than the types themselves.
@available(OSX, introduced: 10.9)
class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
func castToUnavailableProtocol() {
let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51()
let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
class SomeGenericClass<T> { }
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
func GenericWhereClause<T where T: ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
func GenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
// Extensions
extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing extension}}
@available(OSX, introduced: 10.51)
extension ClassAvailableOn10_51 {
func m() {
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing instance method}}
// expected-note@-2 {{add 'if #available' version check}}
}
}
class ClassToExtend { }
@available(OSX, introduced: 10.51)
extension ClassToExtend {
func extensionMethod() { }
@available(OSX, introduced: 10.52)
func extensionMethod10_52() { }
class ExtensionClass { }
// We rely on not allowing nesting of extensions, so test to make sure
// this emits an error.
// CHECK:error: declaration is only valid at file scope
extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}}
}
// We allow protocol extensions for protocols that are less available than the
// conforming class.
extension ClassToExtend : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.51)
extension ClassToExtend { // expected-note {{enclosing scope here}}
@available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}}
func extensionMethod10_9() { }
}
func useUnavailableExtension() {
let o = ClassToExtend()
o.extensionMethod() // expected-error {{'extensionMethod()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Useless #available(...) checks
func functionWithDefaultAvailabilityAndUselessCheck(_ p: Bool) {
// Default availability reflects minimum deployment: 10.9 and up
if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51()
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}} expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
} else {
// Make sure we generate a warning about an unnecessary check even if the else branch of if is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
// This 'if' is strictly to limit the scope of the guard fallthrough
if p {
guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}} expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
// Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
}
// We don't want * generate a warn about useless checks; the check may be required on
// another platform
if #available(iOS 8.0, *) {
}
if #available(OSX 10.51, *) {
// Similarly do not want '*' to generate a warning in a refined TRC.
if #available(iOS 8.0, *) {
}
}
}
@available(OSX, unavailable)
func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}}
func functionWithUnavailableInDeadBranch() {
if #available(iOS 8.0, *) {
} else {
// This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it.
globalFuncAvailableOn10_51() // no-warning
@available(OSX 10.51, *)
func localFuncAvailableOn10_51() {
globalFuncAvailableOn10_52() // no-warning
}
localFuncAvailableOn10_51() // no-warning
// We still want to error on references to explicitly unavailable symbols
// CHECK:error: 'explicitlyUnavailable()' is unavailable
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
guard #available(iOS 8.0, *) else {
globalFuncAvailableOn10_51() // no-warning
// CHECK:error: 'explicitlyUnavailable()' is unavailable
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
}
@available(OSX, introduced: 10.51)
func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}}
if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
// #available(...) outside if statement guards
func injectToOptional<T>(_ v: T) -> T? {
return v
}
if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok
// Refining context inside guard
if #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
// Tests for the guard control construct.
func useGuardAvailable() {
// Guard fallthrough should refine context
guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
return
}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
if globalFuncAvailableOn10_51() > 0 {
guard #available(OSX 10.52, *),
let x = injectToOptional(globalFuncAvailableOn10_52()) else { return }
_ = x
}
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
}
func twoGuardsInSameBlock(_ p: Int) {
if (p > 0) {
guard #available(OSX 10.51, *) else { return }
let _ = globalFuncAvailableOn10_51()
guard #available(OSX 10.52, *) else { return }
let _ = globalFuncAvailableOn10_52()
}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
}
// Refining while loops
while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
globalFuncAvailableOn10_51() > 10 {
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while globalFuncAvailableOn10_51() > 11,
let _ = injectToOptional(5),
#available(OSX 10.52, *) {
let _ = globalFuncAvailableOn10_52();
}
while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
// Tests for Fix-It replacement text
// The whitespace in the replacement text is particularly important here -- it reflects the level
// of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard
// code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we
// take whatever indentation was there before and add 4 spaces to it).
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}}
let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(OSX 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}}
func fixitForReferenceInGlobalFunction() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
public func fixitForReferenceInGlobalFunctionWithDeclModifier() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
@noreturn
func fixitForReferenceInGlobalFunctionWithAttribute() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
func takesAutoclosure(@autoclosure _ c : () -> ()) {
}
class ClassForFixit {
func fixitForReferenceInMethod() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
func fixitForReferenceNestedInMethod() {
func inner() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
let _: () -> () = { () in
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
takesAutoclosure(functionAvailableOn10_51())
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(OSX 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
var fixitForReferenceInPropertyAccessor: Int {
get {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
return 5
}
}
var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing static var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
func fixitForRefInGuardOfIf() {
if (globalFuncAvailableOn10_51() > 1066) {
let _ = 5
let _ = 6
}
// expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(OSX 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-6 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-7 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
}
extension ClassToExtend {
func fixitForReferenceInExtensionMethod() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing extension}} {{1-1=@available(OSX 10.51, *)\n}}
}
}
enum EnumForFixit {
case CaseWithUnavailablePayload(p: ClassAvailableOn10_51)
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing enum}} {{1-1=@available(OSX 10.51, *)\n}}
case CaseWithUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing enum}} {{1-1=@available(OSX 10.51, *)\n}}
}
@objc
class Y {
var z = 0
}
@objc
class X {
var y = Y()
}
func testForFixitWithNestedMemberRefExpr() {
let x = X()
x.y.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(OSX 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}}
// Access via dynamic member reference
let anyX: AnyObject = x
anyX.y?.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(OSX 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}}
}
// Protocol Conformances
protocol ProtocolWithRequirementMentioningUnavailable {
func hasUnavailableParameter(_ p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
// expected-note@-2 * {{add @available attribute to enclosing protocol}}
func hasUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
// expected-note@-2 * {{add @available attribute to enclosing protocol}}
@available(OSX 10.51, *)
func hasUnavailableWithAnnotation(_ p: ClassAvailableOn10_51) -> ClassAvailableOn10_51
}
protocol HasMethodF {
associatedtype T
func f(_ p: T) // expected-note 5{{protocol requirement here}}
}
class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF { // expected-note {{conformance introduced here}}
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF {
// Even though this function is less available than its requirement,
// it is available on a deployment targets, so the conformance is safe.
@available(OSX, introduced: 10.9)
func f(_ p: Int) { }
}
class SuperHasMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class TriesToConformWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-note {{conformance introduced here}}
// The conformance here is generating an error on f in the super class.
}
@available(OSX, introduced: 10.51)
class ConformsWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Limiting this class to only be available on 10.51 and newer means that
// the witness in SuperHasMethodF is safe for the requirement on HasMethodF.
// in order for this class to be referenced we must be running on 10.51 or
// greater.
}
class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Now the witness is this f() (which is always available) and not the f()
// from the super class, so conformance is safe.
override func f(_ p: Int) { }
}
// Attempt to conform in protocol extension with unavailable witness
// in extension
class HasNoMethodF1 { }
extension HasNoMethodF1 : HasMethodF { // expected-note {{conformance introduced here}}
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class HasNoMethodF2 { }
@available(OSX, introduced: 10.51)
extension HasNoMethodF2 : HasMethodF { // expected-note {{conformance introduced here}}
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
@available(OSX, introduced: 10.51)
class HasNoMethodF3 { }
@available(OSX, introduced: 10.51)
extension HasNoMethodF3 : HasMethodF {
// We expect this conformance to succeed because on every version where HasNoMethodF3
// is available, HasNoMethodF3's f() is as available as the protocol requirement
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
protocol HasMethodFOn10_51 {
func f(_ p: Int) // expected-note {{protocol requirement here}}
}
class ConformsToUnavailableProtocolWithUnavailableWitness : HasMethodFOn10_51 {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
class HasNoMethodF4 { }
@available(OSX, introduced: 10.52)
extension HasNoMethodF4 : HasMethodFOn10_51 { // expected-note {{conformance introduced here}}
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodFOn10_51' requires 'f' to be available on OS X 10.51 and newer}}
}
@available(OSX, introduced: 10.51)
protocol HasTakesClassAvailableOn10_51 {
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}}
}
class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { // expected-note {{conformance introduced here}}
@available(OSX, introduced: 10.52)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}}
}
}
class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.51)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) {
}
}
class TakesClassAvailableOn10_51_A { }
extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 { // expected-note {{conformance introduced here}}
@available(OSX, introduced: 10.52)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}}
}
}
class TakesClassAvailableOn10_51_B { }
extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.51)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) {
}
}
// We do not want potential unavailability to play a role in picking a witness for a
// protocol requirement. Rather, the witness should be chosen, regardless of its
// potential unavailability, and then it should be diagnosed if it is less available
// than the protocol requires.
class TestAvailabilityDoesNotAffectWitnessCandidacy : HasMethodF { // expected-note {{conformance introduced here}}
// Test that we choose the more specialized witness even though it is
// less available than the protocol requires and there is a less specialized
// witness that has suitable availability.
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
func f<T>(_ p: T) { }
}
protocol HasUnavailableMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: String)
}
class ConformsWithUnavailableFunction : HasUnavailableMethodF {
@available(OSX, introduced: 10.9)
func f(_ p: String) { }
}
func useUnavailableProtocolMethod(_ h: HasUnavailableMethodF) {
h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func useUnavailableProtocolMethod<H : HasUnavailableMethodF> (_ h: H) {
h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Short-form @available() annotations
@available(OSX 10.51, *)
class ClassWithShortFormAvailableOn10_51 {
}
@available(OSX 10.53, *)
class ClassWithShortFormAvailableOn10_53 {
}
@available(OSX 10.54, *)
class ClassWithShortFormAvailableOn10_54 {
}
@available(OSX 10.9, *)
func funcWithShortFormAvailableOn10_9() {
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX 10.51, *)
func funcWithShortFormAvailableOn10_51() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(iOS 14.0, *)
func funcWithShortFormAvailableOniOS14() {
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
@available(iOS 14.0, OSX 10.53, *)
func funcWithShortFormAvailableOniOS14AndOSX10_53() {
let _ = ClassWithShortFormAvailableOn10_51()
}
// Not idiomatic but we need to be able to handle it.
@available(iOS 8.0, *)
@available(OSX 10.51, *)
func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(OSX 10.51, *)
@available(OSX 10.53, *)
@available(OSX 10.52, *)
func funcWithMultipleShortFormAnnotationsForTheSamePlatform() {
let _ = ClassWithShortFormAvailableOn10_53()
let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available on OS X 10.54 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX 10.9, *)
@available(OSX, unavailable)
func unavailableWins() { } // expected-note {{'unavailableWins()' has been explicitly marked unavailable here}}
func useShortFormAvailable() {
funcWithShortFormAvailableOn10_9()
funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithShortFormAvailableOniOS14()
funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available on OS X 10.53 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available on OS X 10.53 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// CHECK:error: 'unavailableWins()' is unavailable
unavailableWins() // expected-error {{'unavailableWins()' is unavailable}}
}
| 63d46e25d99a11eb5eebe95713d57990 | 44.38589 | 355 | 0.703308 | false | false | false | false |
TintPoint/Overlay | refs/heads/master | Sources/StyleProtocols/TextStyle.swift | mit | 1 | //
// TextStyle.swift
// Overlay
//
// Created by Justin Jia on 8/28/16.
// Copyright © 2016 TintPoint. MIT license.
//
import UIKit
/// A protocol that describes an item that can represent a text.
/// - SeeAlso: `TextStyleGroup`, `TextGroup`
public protocol TextStyle {
/// Returns a `String` that will be used in normal state.
/// - Returns: A `String` that will be used in normal state.
func normal() -> String
}
/// A protocol that describes an item that can represent a text in different states (e.g. disabled).
/// - SeeAlso: `TextStyle`, `TextGroup`
public protocol TextStyleGroup: TextStyle {
/// Returns a `String` that will be used in disabled state.
/// - Returns: A `String` that will be used in disabled state, or `nil` if no text is set.
func disabled() -> String?
/// Returns a `String` that will be used in selected state.
/// - Returns: A `String` that will be used in selected state, or `nil` if no text is set.
func selected() -> String?
/// Returns a `String` that will be used in highlighted state.
/// - Returns: A `String` that will be used in highlighted state, or `nil` if no text is set.
func highlighted() -> String?
/// Returns a `String` that will be used in focused state.
/// - Returns: A `String` that will be used in focused state, or `nil` if no text is set.
func focused() -> String?
}
public extension TextStyleGroup {
/// Returns `nil` by default.
/// - Returns: `nil` by default.
func disabled() -> String? {
return nil
}
/// Returns `nil` by default.
/// - Returns: `nil` by default.
func selected() -> String? {
return nil
}
/// Returns `nil` by default.
/// - Returns: `nil` by default.
func highlighted() -> String? {
return nil
}
/// Returns `nil` by default.
/// - Returns: `nil` by default.
func focused() -> String? {
return nil
}
}
extension String: TextStyle {
public func normal() -> String {
return self
}
}
/// A collection of `TextStyle` that can represent a text in different states (e.g. disabled).
/// - SeeAlso: `TextStyle`, `TextStyleGroup`
public struct TextGroup {
/// The `TextStyle` that will be used in normal state.
private let normalStorage: TextStyle
/// The `TextStyle` that will be used in disabled state, or `nil` if no `TextStyle` is set.
private let disabledStorage: TextStyle?
/// The `TextStyle` that will be used in selected state, or `nil` if no `TextStyle` is set.
private let selectedStorage: TextStyle?
/// The `TextStyle` that will be used in highlighted state, or `nil` if no `TextStyle` is set.
private let highlightedStorage: TextStyle?
/// The `TextStyle` that will be used in focused state, or `nil` if no `TextStyle` is set.
private let focusedStorage: TextStyle?
/// Creates an instance with objects that conforms to `TextStyle`.
/// - Parameter normal: A `TextStyle` that will be used in normal state.
/// - Parameter disabled: A `TextStyle` that will be used in disabled state.
/// - Parameter selected: A `TextStyle` that will be used in selected state.
/// - Parameter highlighted: A `TextStyle` that will be used in highlighted state.
/// - Parameter focused: A `TextStyle` that will be used in focused state.
public init(normal: TextStyle, disabled: TextStyle? = nil, selected: TextStyle? = nil, highlighted: TextStyle? = nil, focused: TextStyle? = nil) {
normalStorage = normal
disabledStorage = disabled
selectedStorage = selected
highlightedStorage = highlighted
focusedStorage = focused
}
}
extension TextGroup: TextStyleGroup {
public func normal() -> String {
return normalStorage.normal()
}
public func disabled() -> String? {
return disabledStorage?.normal()
}
public func selected() -> String? {
return selectedStorage?.normal()
}
public func highlighted() -> String? {
return highlightedStorage?.normal()
}
public func focused() -> String? {
return focusedStorage?.normal()
}
}
/// A protocol that describes a view that its texts can be represented by `TextStyle`.
public protocol TextStyleRepresentable {
/// Returns a `String` that will be used in current state.
/// - Parameter style: A `TextStyle` that represents the text.
/// - Parameter states: An array of `UIControlState` that should be treated as normal state.
/// - Returns: A `String` that will be used in current state, or normal text if no text is set.
func selectedText(from style: TextStyle, usingNormalFor states: [UIControlState]) -> String
/// Customizes a text through a setter method.
/// - Parameter style: A `TextStyle` that represents a text.
/// - Parameter setter: A setter method that will customize a text in different states.
/// - Parameter text: A `String` that will be used.
/// - Parameter state: An `UIControlState` that will use the text.
func customizeText(using style: TextStyle, through setter: (_ text: String?, _ state: UIControlState) -> Void)
}
public extension TextStyleRepresentable {
func selectedText(from style: TextStyle, usingNormalFor states: [UIControlState] = []) -> String {
guard let styleGroup = style as? TextStyleGroup else {
return style.normal()
}
if let view = self as? ViewHighlightable, view.isHighlighted, !states.contains(.highlighted) {
return styleGroup.highlighted() ?? styleGroup.normal()
} else if let view = self as? ViewSelectable, view.isSelected, !states.contains(.selected) {
return styleGroup.selected() ?? styleGroup.normal()
} else if let view = self as? ViewDisable, !view.isEnabled, !states.contains(.disabled) {
return styleGroup.disabled() ?? styleGroup.normal()
} else if let view = self as? ViewFocusable, view.isFocused, !states.contains(.focused) {
return styleGroup.focused() ?? styleGroup.normal()
} else {
return styleGroup.normal()
}
}
func customizeText(using style: TextStyle, through setter: (_ text: String?, _ state: UIControlState) -> Void) {
setter(style.normal(), .normal)
if let styleGroup = style as? TextStyleGroup {
setter(styleGroup.highlighted(), .highlighted)
setter(styleGroup.disabled(), .disabled)
setter(styleGroup.selected(), .selected)
setter(styleGroup.focused(), .focused)
}
}
}
| 31e715876a892954f101af5e086d375a | 38.076923 | 150 | 0.652786 | false | false | false | false |
ArthurGuibert/LiveBusSwift | refs/heads/master | LiveBus/Controller/LiveDeparturesController.swift | mit | 1 | //
// LiveDeparturesController.swift
// LiveBus
//
// Created by Arthur GUIBERT on 01/02/2015.
// Copyright (c) 2015 Arthur GUIBERT. All rights reserved.
//
import UIKit
class LiveDeparturesController: UITableViewController {
var stop: BusStop?
var departures: [Departure]?
let cellHeight: CGFloat = 60.0
override func viewDidLoad() {
super.viewDidLoad()
// Regestering the custom cell we're going to use
var nib = UINib(nibName: "DepartureCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "DepartureCell")
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
title = stop?.name
// Adding the favorite button
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: nil)
let button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0, 53, 32)
button.addTarget(self, action: Selector("setFavorite"), forControlEvents: UIControlEvents.TouchUpInside)
let icon = UILabel(frame: CGRectMake(36, 0, 32, 32))
icon.font = UIFont(name: "dripicons", size: 20)
icon.textColor = UIColor(white: 1, alpha: 1)
icon.text = "\u{e040}"
button.addSubview(icon)
navigationItem.rightBarButtonItem?.customView = button
// Hiding separator
tableView.separatorColor = UIColor(white: 1, alpha: 0)
// Fetching data
Departure.getDepartures(stop!, { (departures: Array<Departure>) -> Void in
self.departures = departures
if self.departures != nil {
self.departures!.sort({$0.departureTime < $1.departureTime})
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
})
}
@IBAction func refresh(sender: UIRefreshControl) {
Departure.getDepartures(stop!, { (departures: Array<Departure>) -> Void in
self.departures = departures
if self.departures != nil {
self.departures!.sort({$0.departureTime < $1.departureTime})
}
// Refreshing on the main thread
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
sender.endRefreshing()
})
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let departure: Departure = departures![indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier("DepartureCell") as DepartureCell
cell.lineLabel.text = departure.line
cell.directionLabel.text = departure.direction
let t = Int(departure.departureTime! / 60)
if t == 0 {
cell.timeLabel.text = "due"
} else {
cell.timeLabel.text = "\(t) min"
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if departures != nil {
return departures!.count
}
return 0
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight
}
func setFavorite() {
let userDefault = NSUserDefaults(suiteName: "group.com.slipcorp.LiveBus")
userDefault?.setObject(stop?.name, forKey: "favoriteStopName")
userDefault?.setObject(stop?.code, forKey: "favoriteStopCode")
userDefault?.synchronize()
}
}
| 60f5280a301aaeedba44430fa462903f | 34.361111 | 137 | 0.608798 | false | false | false | false |
0xcodezero/Vatrena | refs/heads/master | Vatrena/Vatrena/model/VTCartManager.swift | mit | 1 | //
// VTCartManager.swift
// Vatrena
//
// Created by Ahmed Ghalab on 7/29/17.
// Copyright © 2017 Softcare, LLC. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
final class VTCartManager: NSObject {
static let sharedInstance = VTCartManager()
var markets : [VTMarket]?
var cartItems : [VTItem]?
var selectedStore : VTStore?
var databaseRef : DatabaseReference?
private override init() {
self.databaseRef = Database.database().reference()
}
func updateItemInsideCart(store: VTStore?, item: VTItem){
if (item.count ?? 0) == 0 {
if let index = VTCartManager.sharedInstance.cartItems?.index(of: item) {
VTCartManager.sharedInstance.cartItems?.remove(at: index)
}
if cartItems?.count ?? 0 == 0 {
selectedStore = nil
}
}else if !(VTCartManager.sharedInstance.cartItems?.contains(item) ?? false){
VTCartManager.sharedInstance.cartItems?.append(item)
selectedStore = store
}
}
func calclateTotalNumberOfCartItems() -> Int
{
return cartItems?.reduce(0){ $0 + $1.count} ?? 0
}
func generateOrderDetails() -> String {
return VTCartManager.sharedInstance.cartItems?.map({ (cartItem) -> String in
return cartItem.orderDescription
}).joined(separator: "\n") ?? ""
}
func calclateTotalOrderCost() -> Double
{
let cost = cartItems?.reduce(0){ $0 + (Double($1.count!) * $1.price) } ?? 0
return cost
}
func resetCartManager()
{
if let items = cartItems{
for item in items{
item.count = 0
}
cartItems?.removeAll()
selectedStore = nil
}
}
func startLoadingVatrenaData(completion: @escaping( _ result: [VTMarket]) -> Void) {
if let markets = self.markets {
completion(markets)
}else{
self.databaseRef?.child("markets").queryOrdered(byChild: "id").observeSingleEvent(of:.value, with: {[unowned self](snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.cartItems = []
self.markets = []
for snap in snapshot {
if let postDict = snap.value as? [String : Any] {
self.markets?.append(VTMarket.parseNode(postDict))
}
}
completion(self.markets!)
}
})
}
}
}
| b7b4bca195da53b26da10cda19935b3b | 26.701923 | 139 | 0.506421 | false | false | false | false |
square/wire | refs/heads/master | wire-library/wire-runtime-swift/src/main/swift/ProtoEncoder.swift | apache-2.0 | 1 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
A class responsible for turning an in-memory struct generated by the Wire
code generator into serialized bytes in the protocol buffer format that
represent that struct.
General usage will look something like:
```
let encoder = ProtoEncoder()
let data = try encoder.encode(generatedMessageInstance)
```
*/
public final class ProtoEncoder {
// MARK: -
public enum Error: Swift.Error, LocalizedError {
case stringNotConvertibleToUTF8(String)
var localizedDescription: String {
switch self {
case let .stringNotConvertibleToUTF8(string):
return "The string \"\(string)\" could not be converted to UTF8."
}
}
}
// MARK: -
/// The formatting of the output binary data.
public struct OutputFormatting : OptionSet {
/// The format's numerical value.
public let rawValue: UInt
/// Creates an OutputFormatting value with the given raw value.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/**
Produce serialized data with map keys sorted in comparable order.
This is useful for creating deterministic data output but incurs a minor
performance penalty and is not usually necessary in production use cases.
*/
public static let sortedKeys: OutputFormatting = .init(rawValue: 1 << 1)
}
// MARK: - Properties
public var outputFormatting: OutputFormatting = []
// MARK: - Initialization
public init() {}
// MARK: - Public Methods
public func encode<T: ProtoEncodable>(_ value: T) throws -> Data {
// Use the size of the struct as an initial estimate for the space needed.
let structSize = MemoryLayout.size(ofValue: value)
let writer = ProtoWriter(data: .init(capacity: structSize))
writer.outputFormatting = outputFormatting
try value.encode(to: writer)
return Data(writer.buffer, copyBytes: false)
}
}
| daf6cc4c7f93eece9780ec84daf50421 | 28.211111 | 82 | 0.669456 | false | false | false | false |
malt03/DebugHead | refs/heads/master | DebugHead/Classes/DebugHeadWindow.swift | mit | 1 | //
// DebuggerHead.swift
// Pods
//
// Created by Koji Murata on 2016/05/27.
//
//
import UIKit
import BugImageCreator
final class DebugHeadWindow: UIWindow {
init(
menus: [DebugMenu],
center: CGPoint,
sorting: Bool,
footerView: UIView?,
openImmediately: Bool,
sideStickInfo: SideStickInfo?
){
self.footerView = footerView
self.sideStickInfo = sideStickInfo
if sorting {
self.menus = menus.sorted { $0.debugMenuDangerLevel.rawValue < $1.debugMenuDangerLevel.rawValue }
} else {
self.menus = menus
}
super.init(frame: CGRect(origin: .zero, size: DebugHeadWindow.size))
rootViewController = UIStoryboard(name: "DebugMenu", bundle: DebugHeadWindow.bundle).instantiateViewController(withIdentifier: "head")
windowLevel = UIWindow.Level.statusBar - 1
self.center = center
let screenSize = UIScreen.main.bounds.size
ratioCenter = CGPoint(x: center.x / screenSize.width, y: center.y / screenSize.height)
layer.masksToBounds = true
prepareGestureRecognizers()
let key = UIApplication.shared.keyWindow
makeKeyAndVisible()
key?.makeKeyAndVisible()
if openImmediately {
DispatchQueue.main.async { [weak self] in
self?.openDebugMenu()
}
}
}
@objc func openDebugMenu() {
if isOpen { return }
isOpen = true
gestureRecognizers?.forEach { $0.isEnabled = false }
let nc = UIStoryboard(name: "DebugMenu", bundle: DebugHeadWindow.bundle).instantiateInitialViewController() as! UINavigationController
let vc = nc.topViewController as! DebugMenuTableViewController
vc.prepare(self.menus, self.footerView)
rootViewController = nc
nc.view.frame = CGRect(origin: CGPoint(x: -frame.origin.x, y: -frame.origin.y), size: UIScreen.main.bounds.size)
UIView.animate(withDuration: 0.25) {
self.frame = UIScreen.main.bounds
nc.view.frame = UIScreen.main.bounds
UIApplication.shared.setNeedsStatusBarAppearanceUpdate()
}
lastKeyWindow = UIApplication.shared.keyWindow
makeKeyAndVisible()
}
func closeDebugMenu(completion: @escaping () -> Void = {}) {
if !isOpen {
completion()
return
}
isOpen = false
gestureRecognizers?.forEach { $0.isEnabled = true }
UIView.animate(withDuration: 0.25, animations: {
self.frame.size = DebugHeadWindow.size
self.updateCenter()
self.rootViewController?.view.frame = CGRect(origin: CGPoint(x: -self.frame.origin.x, y: -self.frame.origin.y), size: UIScreen.main.bounds.size)
UIApplication.shared.setNeedsStatusBarAppearanceUpdate()
}, completion: { _ in
self.rootViewController = UIStoryboard(name: "DebugMenu", bundle: DebugHeadWindow.bundle).instantiateViewController(withIdentifier: "head")
completion()
})
lastKeyWindow?.makeKeyAndVisible()
}
private static var size: CGSize {
return CGSize(width: 30, height: 30)
}
private let menus: [DebugMenu]
private let footerView: UIView?
private var ratioCenter = CGPoint.zero
private var lastKeyWindow: UIWindow?
private(set) var isOpen = false
private let sideStickInfo: SideStickInfo?
private func prepareGestureRecognizers() {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(openDebugMenu))
addGestureRecognizer(panGestureRecognizer)
addGestureRecognizer(tapGestureRecognizer)
// The force press gesture is recognized as normal tap gesture in simulator when 'UseTrack Force' is enable.
// So we disable to the force press gesture in the simulator.
// Simulator's setting: Hardware -> Touch Pressure -> UseTrack Force ✔︎
#if targetEnvironment(simulator)
#else
let forcePressGestureRecognizer = FourcePressGestureRecognizer(target: self, action: #selector(forcePressed))
addGestureRecognizer(forcePressGestureRecognizer)
#endif
}
private static var bundle: Bundle {
if let path = Bundle(for: DebugHead.self).path(forResource: "DebugHead", ofType: "bundle") {
return Bundle(path: path)!
} else {
return Bundle(for: DebugHead.self)
}
}
@objc private func panned(_ gestureRecognizer: UIPanGestureRecognizer) {
guard let gesturingView = gestureRecognizer.view else { return }
let view = self
switch gestureRecognizer.state {
case .began:
break
case .changed:
let point = gestureRecognizer.translation(in: view)
let center = CGPoint(
x: gesturingView.center.x + point.x,
y: gesturingView.center.y + point.y
)
gesturingView.center = center
gestureRecognizer.setTranslation(.zero, in: view)
default:
guard let sideStickInfo = sideStickInfo else { return }
let safeAreaInset = UIApplication.shared.windows.first?.safeAreaInsets ?? .zero
let mergin = sideStickInfo.mergin
let outlineRect = CGRect(
x: safeAreaInset.left + mergin + DebugHeadWindow.size.width / 2,
y: safeAreaInset.top + mergin + DebugHeadWindow.size.height / 2,
width: UIScreen.main.bounds.width - safeAreaInset.left - safeAreaInset.right - mergin * 2 - DebugHeadWindow.size.width,
height: UIScreen.main.bounds.height - safeAreaInset.top - safeAreaInset.bottom - mergin * 2 - DebugHeadWindow.size.height
)
let initialVelocity = gestureRecognizer.velocity(in: self)
if initialVelocity.length <= 200 || !outlineRect.contains(center) {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: {
self.center = outlineRect.nearSidePoint(for: self.center)
let screenSize = UIScreen.main.bounds.size
self.ratioCenter = CGPoint(x: self.center.x / screenSize.width, y: self.center.y / screenSize.height)
}, completion: nil)
return
}
let intersection = outlineRect.intersection(from: center, velocity: initialVelocity)
UIView.animate(
withDuration: 0.2,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: initialVelocity.length / center.distance(to: intersection),
options: [],
animations: {
self.center = intersection
let screenSize = UIScreen.main.bounds.size
self.ratioCenter = CGPoint(x: self.center.x / screenSize.width, y: self.center.y / screenSize.height)
},
completion: nil
)
}
}
#if targetEnvironment(simulator)
#else
@objc private func forcePressed() {
DebugHead.shared.remove()
}
#endif
private func updateCenter() {
let screenSize = UIScreen.main.bounds.size
center = CGPoint(x: screenSize.width * ratioCenter.x, y: screenSize.height * ratioCenter.y)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 36ec69abfef38e040ceabb8846440724 | 33.9801 | 150 | 0.686673 | false | false | false | false |
webstersx/socket.io-client-swift | refs/heads/master | SocketIOClientSwift/SocketEngine.swift | apache-2.0 | 1 | //
// SocketEngine.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SocketEngine: NSObject, WebSocketDelegate {
private typealias Probe = (msg: String, type: PacketType, data: [NSData]?)
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketEngine"
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let session: NSURLSession!
private let workQueue = NSOperationQueue()
private var closed = false
private var extraHeaders: [String: String]?
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingInterval: Double?
private var pingTimer: NSTimer?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var websocketConnected = false
private(set) var connected = false
private(set) var polling = true
private(set) var websocket = false
weak var client: SocketEngineClient?
var cookies: [NSHTTPCookie]?
var sid = ""
var socketPath = ""
var urlPolling = ""
var urlWebSocket = ""
var ws: WebSocket?
@objc public enum PacketType: Int {
case Open, Close, Ping, Pong, Message, Upgrade, Noop
init?(str: String) {
if let value = Int(str), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client: SocketEngineClient, sessionDelegate: NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: workQueue)
}
public convenience init(client: SocketEngineClient, opts: NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
forcePolling = opts?["forcePolling"] as? Bool ?? false
cookies = opts?["cookies"] as? [NSHTTPCookie]
socketPath = opts?["path"] as? String ?? ""
extraHeaders = opts?["extraHeaders"] as? [String: String]
}
deinit {
Logger.log("Engine is being deinit", type: logType)
stopPolling()
}
private func checkIfMessageIsBase64Binary(var message: String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: message.startIndex.advancedBy(2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
client?.parseBinaryData(data)
}
}
}
public func close(fast fast: Bool) {
Logger.log("Engine is being closed. Fast: %@", type: logType, args: fast)
pingTimer?.invalidate()
closed = true
ws?.disconnect()
if fast || polling {
write("", withType: PacketType.Close, withData: nil)
client?.engineDidClose("Disconnect")
}
stopPolling()
}
private func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return .Left(mutData)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return .Right(str)
}
}
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
if client == nil {
return ("", "")
}
let path = socketPath == "" ? "/socket.io" : socketPath
let url = "\(client!.socketURL)\(path)/?transport="
var urlPolling: String
var urlWebSocket: String
if client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocketAndConnect(connect: Bool) {
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.queue = handleQueue
ws?.delegate = self
if connect {
ws?.connect()
}
}
private func doFastUpgrade() {
if waitingForPoll {
Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: PacketType.Upgrade, datas: nil)
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(req)
}
private func doRequest(req: NSMutableURLRequest) {
if !polling || closed {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
Logger.log("Doing polling request", type: logType)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil || data == nil {
if this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
} else {
Logger.error(err?.localizedDescription ?? "Error", type: this.logType)
}
return
}
Logger.log("Got polling response", type: this.logType)
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(this.parseQueue) {[weak this] in
this?.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}}.resume()
}
private func flushProbeWait() {
Logger.log("Flushing probe wait", type: logType)
dispatch_async(emitQueue) {[weak self] in
if let this = self {
for waiter in this.probeWait {
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
this.probeWait.removeAll(keepCapacity: false)
if this.postWait.count != 0 {
this.flushWaitingForPostToWebSocket()
}
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in postWait {
let len = packet.characters.count
postStr += "\(len):\(packet)"
}
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
if let cookies = cookies {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
waitingForPost = true
Logger.log("POSTing: %@", type: logType, args: postStr)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil && this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
return
} else if err != nil {
NSLog(err?.localizedDescription ?? "Error")
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {[weak this] in
if !(this?.fastUpgrade ?? true) {
this?.flushWaitingForPost()
this?.doPoll()
}
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else {return}
for msg in postWait {
ws.writeString(msg)
}
postWait.removeAll(keepCapacity: true)
}
private func handleClose() {
if let client = client where polling == true {
client.engineDidClose("Disconnect")
}
}
private func handleMessage(message: String) {
client?.parseSocketMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let sid = json?["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json?["upgrades"] as? [String] {
upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0
} else {
upgradeWs = false
}
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect(true)
}
}
} catch {
Logger.error("Error parsing open packet", type: logType)
return
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
}
private func handlePong(pongMessage: String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason: String) {
connected = false
ws?.disconnect()
pingTimer?.invalidate()
waitingForPoll = false
waitingForPost = false
if !closed {
client?.didError(reason)
client?.engineDidClose(reason)
}
}
public func open(opts: [String: AnyObject]? = nil) {
if connected {
Logger.error("Tried to open while connected", type: logType)
client?.didError("Tried to open while connected")
return
}
Logger.log("Starting engine", type: logType)
Logger.log("Handshaking", type: logType)
closed = false
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect(true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(reqPolling)
}
private func parsePollingMessage(str: String) {
guard str.characters.count != 1 else {
return
}
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilStringOccurence(":")) {
let str = reader.read(n)
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
} else {
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
break
}
}
}
private func parseEngineData(data: NSData) {
Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
private func parseEngineMessage(var message: String, fromPolling: Bool) {
Logger.log("Got message: %@", type: logType, args: message)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1]) ?? "") ?? {
self.checkIfMessageIsBase64Binary(message)
return .Noop
}()
switch type {
case PacketType.Message:
message.removeAtIndex(message.startIndex)
handleMessage(message)
case PacketType.Noop:
handleNOOP()
case PacketType.Pong:
handlePong(message)
case PacketType.Open:
message.removeAtIndex(message.startIndex)
handleOpen(message)
case PacketType.Close:
handleClose()
default:
Logger.log("Got unknown packet type", type: logType)
}
}
private func probeWebSocket() {
if websocketConnected {
sendWebSocketMessage("probe", withType: PacketType.Ping)
}
}
/// Send an engine message (4)
public func send(msg: String, withData datas: [NSData]?) {
if probing {
probeWait.append((msg, PacketType.Message, datas))
} else {
write(msg, withType: PacketType.Message, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: PacketType.Ping, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg: String, withType type: PacketType,
datas:[NSData]? = nil) {
Logger.log("Sending poll: %@ as type: %@", type: logType, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
postWait.append(strMsg)
for data in datas ?? [] {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str: String, withType type: PacketType,
datas:[NSData]? = nil) {
Logger.log("Sending ws: %@ as type: %@", type: logType, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas ?? [] {
if case let Either.Left(bin) = createBinaryDataForSend(data) {
ws?.writeData(bin)
}
}
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
func stopPolling() {
session.finishTasksAndInvalidate()
}
private func upgradeTransport() {
if websocketConnected {
Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: PacketType.Noop)
// After this point, we should not send anymore polling messages
}
}
/**
Write a message, independent of transport.
*/
public func write(msg: String, withType type: PacketType, withData data: [NSData]?) {
dispatch_async(emitQueue) {
if self.connected {
if self.websocket {
Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendPollMessage(msg, withType: type, datas: data)
}
}
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
websocketConnected = true
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
websocketConnected = false
probing = false
if closed {
client?.engineDidClose("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
client?.didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
parseEngineData(data)
}
}
| dbdecaad3d4273503db119e9651fccba | 31.153521 | 119 | 0.557712 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/AutoDiff/Sema/differentiable_func_type.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -typecheck -verify %s
import _Differentiation
//===----------------------------------------------------------------------===//
// Basic @differentiable function types.
//===----------------------------------------------------------------------===//
// expected-error @+1 {{@differentiable attribute only applies to function types}}
let _: @differentiable Float
let _: @differentiable (Float) -> Float
let _: @differentiable (Float) throws -> Float
//===----------------------------------------------------------------------===//
// Type differentiability
//===----------------------------------------------------------------------===//
struct NonDiffType { var x: Int }
// FIXME: Properly type-check parameters and the result's differentiability
// expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable (NonDiffType) -> Float
// Emit `@noDerivative` fixit iff there is at least one valid differentiability parameter.
// expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'; did you want to add '@noDerivative' to this parameter?}} {{32-32=@noDerivative }}
let _: @differentiable (Float, NonDiffType) -> Float
// expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
let _: @differentiable(linear) (Float) -> NonDiffType
// Emit `@noDerivative` fixit iff there is at least one valid linearity parameter.
// expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'; did you want to add '@noDerivative' to this parameter?}} {{40-40=@noDerivative }}
let _: @differentiable(linear) (Float, NonDiffType) -> Float
// expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable (Float) -> NonDiffType
// expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
let _: @differentiable(linear) (Float) -> NonDiffType
let _: @differentiable(linear) (Float) -> Float
// expected-error @+1 {{result type '@differentiable (U) -> Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
func test1<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> @differentiable (U) -> Float) {}
// expected-error @+1 {{result type '(U) -> Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
func test2<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> (U) -> Float) {}
// expected-error @+2 {{result type 'Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
// expected-error @+1 {{result type '@differentiable (U) -> Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
func test3<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> @differentiable (U) -> Int) {}
// expected-error @+1 {{result type '(U) -> Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
func test4<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> (U) -> Int) {}
//===----------------------------------------------------------------------===//
// Function conversion
//===----------------------------------------------------------------------===//
/// Function with similar signature as `gradient`, for testing purposes.
func fakeGradient<T, U: FloatingPoint>(of f: @differentiable (T) -> U) {}
func takesOpaqueClosure(f: @escaping (Float) -> Float) {
// expected-note @-1 {{did you mean to take a '@differentiable' closure?}} {{38-38=@differentiable }}
// expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}}
fakeGradient(of: f)
}
let globalAddOne: (Float) -> Float = { $0 + 1 }
// expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}}
fakeGradient(of: globalAddOne)
func someScope() {
let localAddOne: (Float) -> Float = { $0 + 1 }
// expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}}
fakeGradient(of: globalAddOne)
// expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}}
fakeGradient(of: localAddOne)
// The following case is okay during type checking, but will fail in the AD transform.
fakeGradient { localAddOne($0) }
}
func addOne(x: Float) -> Float { x + 1 }
fakeGradient(of: addOne) // okay
extension Float {
static func addOne(x: Float) -> Float { x + 1 }
func addOne(x: Float) -> Float { x + 1 }
}
fakeGradient(of: Float.addOne) // okay
fakeGradient(of: Float(1.0).addOne) // okay
// TODO(TF-908): Remove this test once linear-to-differentiable conversion is supported.
func linearToDifferentiable(_ f: @escaping @differentiable(linear) (Float) -> Float) {
// expected-error @+1 {{conversion from '@differentiable(linear)' to '@differentiable' is not yet supported}}
_ = f as @differentiable (Float) -> Float
}
func differentiableToLinear(_ f: @escaping @differentiable (Float) -> Float) {
// expected-error @+1 {{a '@differentiable(linear)' function can only be formed from a reference to a 'func' or 'init' or a literal closure}}
_ = f as @differentiable(linear) (Float) -> Float
}
struct Struct: Differentiable {
var x: Float
}
let _: @differentiable (Float) -> Struct = Struct.init
//===----------------------------------------------------------------------===//
// Parameter selection (@noDerivative)
//===----------------------------------------------------------------------===//
// expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
let _: @noDerivative Float
// expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
let _: (@noDerivative Float) -> Float
// expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
let _: (@noDerivative Float, Float) -> Float
let _: @differentiable (Float, @noDerivative Float) -> Float // okay
// expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
let _: (Float) -> @noDerivative Float
// expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
let _: @differentiable (Float) -> @noDerivative Float
// expected-error @+2 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}}
// expected-error @+1 {{'@noDerivative' must not be used on variadic parameters}}
let _: (Float, @noDerivative Float...) -> Float
let _: @differentiable (@noDerivative Float, Float) -> Float
// expected-error @+1 {{'@noDerivative' must not be used on variadic parameters}}
let _: @differentiable (Float, @noDerivative Float...) -> Float
//===----------------------------------------------------------------------===//
// Inferred conformances
//===----------------------------------------------------------------------===//
let diffFunc: @differentiable (Float) -> Float
let linearFunc: @differentiable(linear) (Float) -> Float
func inferredConformances<T, U>(_: @differentiable (T) -> U) {}
func inferredConformancesLinear<T, U>(_: @differentiable(linear) (T) -> U) {}
inferredConformances(diffFunc)
inferredConformancesLinear(linearFunc)
func inferredConformancesResult<T, U>() -> @differentiable (T) -> U {}
func inferredConformancesResultLinear<T, U>() -> @differentiable(linear) (T) -> U {}
let diffFuncWithNondiff: @differentiable (Float, @noDerivative Int) -> Float
let linearFuncWithNondiff: @differentiable(linear) (Float, @noDerivative Int) -> Float
func inferredConformances<T, U, V>(_: @differentiable (T, @noDerivative U) -> V) {}
func inferredConformancesLinear<T, U, V>(_: @differentiable(linear) (T, @noDerivative U) -> V) {}
inferredConformances(diffFuncWithNondiff)
inferredConformancesLinear(linearFuncWithNondiff)
struct Vector<T> {
var x, y: T
}
extension Vector: Equatable where T: Equatable {}
extension Vector: AdditiveArithmetic where T: AdditiveArithmetic {
static var zero: Self { fatalError() }
static func + (lhs: Self, rhs: Self) -> Self { fatalError() }
static func - (lhs: Self, rhs: Self) -> Self { fatalError() }
}
extension Vector: Differentiable where T: Differentiable {
struct TangentVector: Equatable, AdditiveArithmetic, Differentiable {
var x, y: T.TangentVector
static var zero: Self { fatalError() }
static func + (lhs: Self, rhs: Self) -> Self { fatalError() }
static func - (lhs: Self, rhs: Self) -> Self { fatalError() }
typealias TangentVector = Self
}
mutating func move(along direction: TangentVector) { fatalError() }
}
func inferredConformancesGeneric<T, U>(_: @differentiable (Vector<T>) -> Vector<U>) {}
// expected-error @+4 {{generic signature requires types 'Vector<T>' and 'Vector<T>.TangentVector' to be the same}}
// expected-error @+3 {{generic signature requires types 'Vector<U>' and 'Vector<U>.TangentVector' to be the same}}
// expected-error @+2 {{parameter type 'Vector<T>' does not conform to 'Differentiable' and satisfy 'Vector<T> == Vector<T>.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
// expected-error @+1 {{result type 'Vector<U>' does not conform to 'Differentiable' and satisfy 'Vector<U> == Vector<U>.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
func inferredConformancesGenericLinear<T, U>(_: @differentiable(linear) (Vector<T>) -> Vector<U>) {}
func nondiff(x: Vector<Int>) -> Vector<Int> {}
// expected-error @+1 {{global function 'inferredConformancesGeneric' requires that 'Int' conform to 'Differentiable}}
inferredConformancesGeneric(nondiff)
// expected-error @+1 {{global function 'inferredConformancesGenericLinear' requires that 'Int' conform to 'Differentiable}}
inferredConformancesGenericLinear(nondiff)
func diff(x: Vector<Float>) -> Vector<Float> {}
inferredConformancesGeneric(diff) // okay!
func inferredConformancesGenericResult<T, U>() -> @differentiable (Vector<T>) -> Vector<U> {}
// expected-error @+4 {{generic signature requires types 'Vector<T>' and 'Vector<T>.TangentVector' to be the same}}
// expected-error @+3 {{generic signature requires types 'Vector<U>' and 'Vector<U>.TangentVector' to be the same}}
// expected-error @+2 {{parameter type 'Vector<T>' does not conform to 'Differentiable' and satisfy 'Vector<T> == Vector<T>.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
// expected-error @+1 {{result type 'Vector<U>' does not conform to 'Differentiable' and satisfy 'Vector<U> == Vector<U>.TangentVector', but the enclosing function type is '@differentiable(linear)'}}
func inferredConformancesGenericResultLinear<T, U>() -> @differentiable(linear) (Vector<T>) -> Vector<U> {}
struct Linear<T> {
var x, y: T
}
extension Linear: Equatable where T: Equatable {}
extension Linear: AdditiveArithmetic where T: AdditiveArithmetic {}
extension Linear: Differentiable where T: Differentiable, T == T.TangentVector {
typealias TangentVector = Self
}
// expected-note @+1 2 {{where 'T' = 'Int'}}
func inferredConformancesGeneric<T, U>(_: @differentiable (Linear<T>) -> Linear<U>) {}
// expected-note @+1 2 {{where 'T' = 'Int'}}
func inferredConformancesGenericLinear<T, U>(_: @differentiable(linear) (Linear<T>) -> Linear<U>) {}
func nondiff(x: Linear<Int>) -> Linear<Int> {}
// expected-error @+1 {{global function 'inferredConformancesGeneric' requires that 'Int' conform to 'Differentiable}}
inferredConformancesGeneric(nondiff)
// expected-error @+1 {{global function 'inferredConformancesGenericLinear' requires that 'Int' conform to 'Differentiable}}
inferredConformancesGenericLinear(nondiff)
func diff(x: Linear<Float>) -> Linear<Float> {}
inferredConformancesGeneric(diff) // okay!
func inferredConformancesGenericResult<T, U>() -> @differentiable (Linear<T>) -> Linear<U> {}
func inferredConformancesGenericResultLinear<T, U>() -> @differentiable(linear) (Linear<T>) -> Linear<U> {}
| a450c7255e3cdfc03412d3e49891db5b | 55.215859 | 289 | 0.677533 | false | false | false | false |
ihomway/RayWenderlichCourses | refs/heads/master | ServerSideSwiftWithPerfect/hello-perfect/Sources/main.swift | mit | 1 | import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
let server = HTTPServer()
server.serverPort = 8080
server.documentRoot = "webroot"
var routes = Routes()
routes.add(method: .get, uri: "/") { request, response in
response.setBody(string: "Hello, Perfect!")
.completed()
}
func returnJSONMessage(message: String, response: HTTPResponse) {
do {
try response.setBody(json: ["message": message])
.setHeader(.contentType, value: "application/json")
.completed()
} catch {
response.setBody(string: "Error handling request: \(error)")
.completed(status: .internalServerError)
}
}
routes.add(method: .get, uri: "/hello") { request, response in
returnJSONMessage(message: "Hello, JSON!", response: response)
}
routes.add(method: .get, uri: "/hello/there") { request, response in
returnJSONMessage(message: "I am tired of saying hello!", response: response)
}
routes.add(method: .get, uri: "/beers/{num_beers}") { request, response in
guard let numBeersString = request.urlVariables["num_beers"],
let numBeersInt = Int(numBeersString) else {
response.completed(status: .badRequest)
return
}
returnJSONMessage(message: "Take one down, pass it around, \(numBeersInt - 1) bottles of beer on the wall...", response: response)
}
routes.add(method: .post, uri: "post") { request, response in
guard let name = request.param(name: "name") else {
response.completed(status: .badRequest)
return
}
returnJSONMessage(message: "Hello, \(name)!", response: response)
}
server.addRoutes(routes)
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
print("Network error thrown: \(err) \(msg)")
}
| 78e1d501e9a71214320bcb675a9da315 | 26.633333 | 131 | 0.715923 | false | false | false | false |
apple/swift | refs/heads/main | SwiftCompilerSources/Sources/Optimizer/TestPasses/EscapeInfoDumper.swift | apache-2.0 | 1 | //===--- EscapeInfoDumper.swift - Dumps escape information ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// Dumps the results of escape analysis.
///
/// Dumps the EscapeInfo query results for all `alloc_stack` instructions in a function.
///
/// This pass is used for testing EscapeInfo.
let escapeInfoDumper = FunctionPass(name: "dump-escape-info", {
(function: Function, context: PassContext) in
print("Escape information for \(function.name):")
struct Visitor : EscapeVisitorWithResult {
var result: Set<String> = Set()
mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {
if operand.instruction is ReturnInst {
result.insert("return[\(path.projectionPath)]")
return .ignore
}
return .continueWalk
}
mutating func visitDef(def: Value, path: EscapePath) -> DefResult {
guard let arg = def as? FunctionArgument else {
return .continueWalkUp
}
result.insert("arg\(arg.index)[\(path.projectionPath)]")
return .walkDown
}
}
for inst in function.instructions {
if let allocRef = inst as? AllocRefInst {
let resultStr: String
if let result = allocRef.visit(using: Visitor(), context) {
if result.isEmpty {
resultStr = " - "
} else {
resultStr = Array(result).sorted().joined(separator: ",")
}
} else {
resultStr = "global"
}
print("\(resultStr): \(allocRef)")
}
}
print("End function \(function.name)\n")
})
/// Dumps the results of address-related escape analysis.
///
/// Dumps the EscapeInfo query results for addresses escaping to function calls.
/// The `fix_lifetime` instruction is used as marker for addresses and values to query.
///
/// This pass is used for testing EscapeInfo.
let addressEscapeInfoDumper = FunctionPass(name: "dump-addr-escape-info", {
(function: Function, context: PassContext) in
print("Address escape information for \(function.name):")
var valuesToCheck = [Value]()
var applies = [Instruction]()
for inst in function.instructions {
switch inst {
case let fli as FixLifetimeInst:
valuesToCheck.append(fli.operand)
case is FullApplySite:
applies.append(inst)
default:
break
}
}
struct Visitor : EscapeVisitor {
let apply: Instruction
mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {
let user = operand.instruction
if user == apply {
return .abort
}
if user is ReturnInst {
// Anything which is returned cannot escape to an instruction inside the function.
return .ignore
}
return .continueWalk
}
}
// test `isEscaping(addressesOf:)`
for value in valuesToCheck {
print("value:\(value)")
for apply in applies {
let path = AliasAnalysis.getPtrOrAddressPath(for: value)
if value.at(path).isAddressEscaping(using: Visitor(apply: apply), context) {
print(" ==> \(apply)")
} else {
print(" - \(apply)")
}
}
}
// test `canReferenceSameField` for each pair of `fix_lifetime`.
if !valuesToCheck.isEmpty {
for lhsIdx in 0..<(valuesToCheck.count - 1) {
for rhsIdx in (lhsIdx + 1) ..< valuesToCheck.count {
print("pair \(lhsIdx) - \(rhsIdx)")
let lhs = valuesToCheck[lhsIdx]
let rhs = valuesToCheck[rhsIdx]
print(lhs)
print(rhs)
let projLhs = lhs.at(AliasAnalysis.getPtrOrAddressPath(for: lhs))
let projRhs = rhs.at(AliasAnalysis.getPtrOrAddressPath(for: rhs))
let mayAlias = projLhs.canAddressAlias(with: projRhs, context)
if mayAlias != projRhs.canAddressAlias(with: projLhs, context) {
fatalError("canAddressAlias(with:) must be symmetric")
}
let addrReachable: Bool
if lhs.type.isAddress && !rhs.type.isAddress {
let anythingReachableFromRhs = rhs.at(SmallProjectionPath(.anything))
addrReachable = projLhs.canAddressAlias(with: anythingReachableFromRhs, context)
if mayAlias && !addrReachable {
fatalError("mayAlias implies addrReachable")
}
} else {
addrReachable = false
}
if mayAlias {
print("may alias")
} else if addrReachable {
print("address reachable but no alias")
} else {
print("no alias")
}
}
}
}
print("End function \(function.name)\n")
})
| 3466a6cef9e9cac9a38c6687cfaccd7f | 30.245283 | 90 | 0.619565 | false | false | false | false |
LY-Coder/LYPlayer | refs/heads/master | LYPlayerExample/LYPlayer/LYSeekView.swift | mit | 1 | //
// LYSeekView.swift
// LYPlayerExample
//
// Created by LY_Coder on 2018/1/30.
// Copyright © 2018年 LYCoder. All rights reserved.
//
import UIKit
import AVFoundation
class LYSeekView: UIView {
static var shared = LYSeekView()
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 8.5
self.layer.masksToBounds = true
setupUI()
setupUIFrame()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/** 时间转分秒 */
func timeToSeconds(time: CMTime?) -> String {
// 计算分钟
let minute = Int(time?.seconds ?? 0.0) / 60
// 计算秒
let seconds = Int(time?.seconds ?? 0.0) % 60
return String(format: "%02d:%02d", arguments: [minute, seconds])
}
/** 调整播放进度 */
func seek(to time: CMTime, with currentTime: CMTime, item: AVPlayerItem) {
self.alpha = 1
// 修改后的时间字符串
let toTimeString = timeToSeconds(time: time)
// 当前的时间字符串
let totalTimeString = timeToSeconds(time: item.duration)
timeLabel.text = "\(toTimeString)/\(totalTimeString)"
let attributeString = NSMutableAttributedString(string: "\(toTimeString)/\(totalTimeString)")
attributeString.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: NSRange(location: 0, length: 5))
timeLabel.attributedText = attributeString
// 设置图标
if time.seconds > currentTime.seconds {
// 快进
iconView.image = UIImage("LYPlayer_forward")
} else {
// 快退
iconView.image = UIImage("LYPlayer_backward")
}
// 获取图片
let generator = AVAssetImageGenerator(asset: item.asset)
// 取消快速滑动时 尚未提供的图像
generator.cancelAllCGImageGeneration()
weak var weakSelf = self
generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)], completionHandler: { (requestedTime, img, actualTime, result, error) in
if result == AVAssetImageGeneratorResult.succeeded {
// 回主线程
DispatchQueue.main.async(execute: {
weakSelf?.videoImgView.image = UIImage(cgImage: img!)
})
}
if result == AVAssetImageGeneratorResult.failed {
print("Failed with error:\(String(describing: error?.localizedDescription))")
}
if result == AVAssetImageGeneratorResult.cancelled {
print("AVAssetImageGeneratorCancelled")
}
})
// 消失动画
UIView.animate(withDuration: 1.0, delay: 1.7, options: .curveLinear, animations: {
self.alpha = 0.0
}) { (false) in }
}
// 获取window
lazy var keyWindow: UIWindow = {
let keyWindow = UIApplication.shared.keyWindow!
return keyWindow
}()
lazy var visual: UIVisualEffectView = {
let blur = UIBlurEffect(style: .light)
let visual = UIVisualEffectView(effect: blur)
return visual
}()
lazy var iconView: UIImageView = {
let iconView = UIImageView()
return iconView
}()
lazy var timeLabel: UILabel = {
let timeLabel = UILabel()
timeLabel.font = UIFont.systemFont(ofSize: 14)
timeLabel.textAlignment = .right
return timeLabel
}()
lazy var videoImgView: UIImageView = {
let videoImgView = UIImageView()
videoImgView.backgroundColor = UIColor.black
videoImgView.layer.cornerRadius = 8.5
videoImgView.layer.masksToBounds = true
return videoImgView
}()
func setupUI() {
addSubview(visual)
keyWindow.addSubview(self)
addSubview(iconView)
addSubview(timeLabel)
addSubview(videoImgView)
}
func setupUIFrame() {
// 将当前视图添加到windoiw上
self.snp.makeConstraints { (make) in
make.center.equalTo(keyWindow)
make.size.equalTo(CGSize(width: 180, height: 155))
}
visual.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
iconView.snp.makeConstraints { (make) in
make.top.left.equalTo(self).offset(10)
make.size.equalTo(CGSize(width: 30, height: 25))
}
timeLabel.snp.makeConstraints { (make) in
make.right.equalTo(self).offset(-10)
make.top.equalTo(self).offset(15)
make.size.equalTo(CGSize(width: 100, height: 15))
}
videoImgView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(50, 10, 10, 10))
}
}
}
| 4096d20f6075c68f8c0c593341677e47 | 28.169591 | 153 | 0.560144 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/AccountRecovery/TradingAccountWarning/TradingAccountWarningView.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import Localization
import SwiftUI
public struct TradingAccountWarningView: View {
private typealias LocalizedStrings = LocalizationConstants.FeatureAuthentication.TradingAccountWarning
private enum Layout {
static let imageSideLength: CGFloat = 72
static let messageFontSize: CGFloat = 16
static let messageLineSpacing: CGFloat = 4
static let messageBottomPadding: CGFloat = 10
static let bottomPadding: CGFloat = 34
static let leadingPadding: CGFloat = 24
static let trailingPadding: CGFloat = 24
static let titleTopPadding: CGFloat = 16
static let buttonBottomPadding: CGFloat = 10
}
public var cancelButtonTapped: (() -> Void)?
public var logoutButtonTapped: (() -> Void)?
private let walletIdHint: String
public init(
walletIdHint: String
) {
self.walletIdHint = walletIdHint
}
public var body: some View {
VStack {
Spacer()
Image.CircleIcon.warning
.frame(width: Layout.imageSideLength, height: Layout.imageSideLength)
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.image)
Text(LocalizedStrings.title)
.textStyle(.title)
.padding(.top, Layout.titleTopPadding)
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.title)
Text(LocalizedStrings.message)
.font(Font(weight: .medium, size: Layout.messageFontSize))
.foregroundColor(.textSubheading)
.lineSpacing(Layout.messageLineSpacing)
.padding(.bottom, Layout.messageBottomPadding)
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.message)
Text(LocalizedStrings.walletIdMessagePrefix + walletIdHint)
.font(Font(weight: .medium, size: Layout.messageFontSize))
.foregroundColor(.textBody)
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.walletIdMessagePrefix)
Spacer()
PrimaryButton(title: LocalizedStrings.Button.logout) {
logoutButtonTapped?()
}
.padding(.bottom, Layout.buttonBottomPadding)
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.logoutButton)
MinimalButton(title: LocalizedStrings.Button.cancel) {
cancelButtonTapped?()
}
.accessibility(identifier: AccessibilityIdentifiers.TradingAccountWarningScreen.cancel)
}
.multilineTextAlignment(.center)
.padding(
EdgeInsets(
top: 0,
leading: Layout.leadingPadding,
bottom: Layout.bottomPadding,
trailing: Layout.trailingPadding
)
)
}
}
#if DEBUG
struct TradingAccountWarningView_Previews: PreviewProvider {
static var previews: some View {
TradingAccountWarningView(
walletIdHint: ""
)
}
}
#endif
| 4154dc99148f2546ba9633cecb850cb3 | 34.48913 | 118 | 0.650536 | false | false | false | false |
codelynx/Metal2DScrollable | refs/heads/master | Metal2DScroll/GeoUtils.swift | mit | 1 | //
// GeoUtils.swift
// Metal2DScroll
//
// Created by Kaz Yoshikawa on 1/4/16.
//
//
import Foundation
import CoreGraphics
import QuartzCore
import simd
infix operator •
infix operator ×
protocol FloatCovertible {
var floatValue: Float { get }
}
extension CGFloat: FloatCovertible {
var floatValue: Float { return Float(self) }
}
extension Int: FloatCovertible {
var floatValue: Float { return Float(self) }
}
struct Point: Hashable {
var x: Float
var y: Float
static func - (lhs: Point, rhs: Point) -> Point {
return Point(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
static func + (lhs: Point, rhs: Point) -> Point {
return Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func * (lhs: Point, rhs: Float) -> Point {
return Point(x: lhs.x * rhs, y: lhs.y * rhs)
}
static func / (lhs: Point, rhs: Float) -> Point {
return Point(x: lhs.x / rhs, y: lhs.y / rhs)
}
static func * (lhs: Point, rhs: Point) -> Float { // dot product
return lhs.x * rhs.x + lhs.y * rhs.y
}
static func × (lhs: Point, rhs: Point) -> Float { // cross product
return lhs.x * rhs.y - lhs.y * rhs.x
}
var length²: Float {
return (x * x) + (y * y)
}
var length: Float {
return sqrt(self.length²)
}
var normalized: Point {
let length = self.length
return Point(x: x/length, y: y/length)
}
func angle(to: Point) -> Float {
return atan2(to.y - self.y, to.x - self.x)
}
func angle(from: Point) -> Float {
return atan2(self.y - from.y, self.x - from.x)
}
static func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.y && lhs.y == rhs.y
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.x)
hasher.combine(self.y)
}
}
extension Point {
init<X: FloatCovertible, Y: FloatCovertible>(_ x: X, _ y: Y) {
self.x = x.floatValue
self.y = y.floatValue
}
init<X: FloatCovertible, Y: FloatCovertible>(x: X, y: Y) {
self.x = x.floatValue
self.y = y.floatValue
}
}
struct Size {
var width: Float
var height: Float
init<W: FloatCovertible, H: FloatCovertible>(_ width: W, _ height: H) {
self.width = width.floatValue
self.height = height.floatValue
}
init<W: FloatCovertible, H: FloatCovertible>(width: W, height: H) {
self.width = width.floatValue
self.height = height.floatValue
}
}
struct Rect: CustomStringConvertible {
var origin: Point
var size: Size
init(origin: Point, size: Size) {
self.origin = origin; self.size = size
}
init(_ origin: Point, _ size: Size) {
self.origin = origin; self.size = size
}
init<X: FloatCovertible, Y: FloatCovertible, W: FloatCovertible, H: FloatCovertible>(_ x: X, _ y: Y, _ width: W, _ height: H) {
self.origin = Point(x: x, y: y)
self.size = Size(width: width, height: height)
}
init<X: FloatCovertible, Y: FloatCovertible, W: FloatCovertible, H: FloatCovertible>(x: X, y: Y, width: W, height: H) {
self.origin = Point(x: x, y: y)
self.size = Size(width: width, height: height)
}
var minX: Float { return min(origin.x, origin.x + size.width) }
var maxX: Float { return max(origin.x, origin.x + size.width) }
var midX: Float { return (origin.x + origin.x + size.width) / 2.0 }
var minY: Float { return min(origin.y, origin.y + size.height) }
var maxY: Float { return max(origin.y, origin.y + size.height) }
var midY: Float { return (origin.y + origin.y + size.height) / 2.0 }
var cgRectValue: CGRect { return CGRect(x: CGFloat(origin.x), y: CGFloat(origin.y), width: CGFloat(size.width), height: CGFloat(size.height)) }
var description: String { return "{Rect: (\(origin.x),\(origin.y))-(\(size.width), \(size.height))}" }
}
// MARK: -
// MARK: -
extension CGPoint {
init(_ point: Point) {
self.init(x: CGFloat(point.x), y: CGFloat(point.y))
}
static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
}
static func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x / rhs, y: lhs.y / rhs)
}
static func * (lhs: CGPoint, rhs: CGPoint) -> CGFloat { // dot product
return lhs.x * rhs.x + lhs.y * rhs.y
}
static func ⨯ (lhs: CGPoint, rhs: CGPoint) -> CGFloat { // cross product
return lhs.x * rhs.y - lhs.y * rhs.x
}
static func × (lhs: CGPoint, rhs: CGPoint) -> CGFloat { // cross product
return lhs.x * rhs.y - lhs.y * rhs.x
}
var length²: CGFloat {
return (x * x) + (y * y)
}
var length: CGFloat {
return sqrt(self.length²)
}
var normalized: CGPoint {
let length = self.length
return CGPoint(x: x/length, y: y/length)
}
}
extension CGSize {
init(_ size: Size) {
self.init(width: CGFloat(size.width), height: CGFloat(size.height))
}
}
extension CGRect {
init(_ rect: Rect) {
self.init(origin: CGPoint(rect.origin), size: CGSize(rect.size))
}
}
func CGRectMakeAspectFill(_ imageSize: CGSize, _ bounds: CGRect) -> CGRect {
let result: CGRect
let margin: CGFloat
let horizontalRatioToFit = bounds.size.width / imageSize.width
let verticalRatioToFit = bounds.size.height / imageSize.height
let imageHeightWhenItFitsHorizontally = horizontalRatioToFit * imageSize.height
let imageWidthWhenItFitsVertically = verticalRatioToFit * imageSize.width
let minX = bounds.minX
let minY = bounds.minY
if (imageHeightWhenItFitsHorizontally > bounds.size.height) {
margin = (imageHeightWhenItFitsHorizontally - bounds.size.height) * 0.5
result = CGRect(x: minX, y: minY - margin, width: imageSize.width * horizontalRatioToFit, height: imageSize.height * horizontalRatioToFit)
}
else {
margin = (imageWidthWhenItFitsVertically - bounds.size.width) * 0.5
result = CGRect(x: minX - margin, y: minY, width: imageSize.width * verticalRatioToFit, height: imageSize.height * verticalRatioToFit)
}
return result;
}
func CGRectMakeAspectFit(_ imageSize: CGSize, _ bounds: CGRect) -> CGRect {
let minX = bounds.minX
let minY = bounds.minY
let widthRatio = bounds.size.width / imageSize.width
let heightRatio = bounds.size.height / imageSize.height
let ratio = min(widthRatio, heightRatio)
let width = imageSize.width * ratio
let height = imageSize.height * ratio
let xmargin = (bounds.size.width - width) / 2.0
let ymargin = (bounds.size.height - height) / 2.0
return CGRect(x: minX + xmargin, y: minY + ymargin, width: width, height: height)
}
func CGSizeMakeAspectFit(_ imageSize: CGSize, frameSize: CGSize) -> CGSize {
let widthRatio = frameSize.width / imageSize.width
let heightRatio = frameSize.height / imageSize.height
let ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio
let width = imageSize.width * ratio
let height = imageSize.height * ratio
return CGSize(width: width, height: height)
}
extension simd_float4x4 {
init(_ transform: CGAffineTransform) {
let t = CATransform3DMakeAffineTransform(transform)
self = simd_float4x4([
[Float(t.m11), Float(t.m12), Float(t.m13), Float(t.m14)],
[Float(t.m21), Float(t.m22), Float(t.m23), Float(t.m24)],
[Float(t.m31), Float(t.m32), Float(t.m33), Float(t.m34)],
[Float(t.m41), Float(t.m42), Float(t.m43), Float(t.m44)]
])
}
}
| 8cd81cc4ec592aca862398694a5f7c7f | 25.338182 | 144 | 0.667403 | false | false | false | false |
easyui/EZPlayer | refs/heads/master | EZPlayerExample/EZPlayerExample/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// EZPlayerExample
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
/*
let overlayClass = NSClassFromString("UIDebuggingInformationOverlay") as? UIWindow.Type
_ = overlayClass?.perform(NSSelectorFromString("prepareDebuggingOverlay"))
let overlay = overlayClass?.perform(NSSelectorFromString("overlay")).takeUnretainedValue() as? UIWindow
_ = overlay?.perform(NSSelectorFromString("toggleVisibility"))
*/
//设置pip需要添加
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playback)
try audioSession.setActive(true, options: [])
} catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 21fc98ef6dd92536de4a554c7a669cca | 47.35 | 285 | 0.730782 | false | false | false | false |
dnevera/IMProcessing | refs/heads/master | IMProcessing/Classes/Adjustments/IMPWBFilter.swift | mit | 1 | //
// IMPWBFilter.swift
// IMProcessing
//
// Created by denis svinarchuk on 19.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import Foundation
import Metal
/// White balance correction filter
public class IMPWBFilter:IMPFilter,IMPAdjustmentProtocol{
/// Default WB adjustment
public static let defaultAdjustment = IMPWBAdjustment(
/// @brief default dominant color of the image
///
dominantColor: float4([0.5, 0.5, 0.5, 0.5]),
/// @brief Blending mode and opacity
///
blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1)
)
/// Adjust filter
public var adjustment:IMPWBAdjustment!{
didSet{
updateBuffer(&adjustmentBuffer, context:context, adjustment:&adjustment, size:sizeof(IMPWBAdjustment))
dirty = true
}
}
public var adjustmentBuffer:MTLBuffer?
public var kernel:IMPFunction!
/// Create WB filter.
///
/// - parameter context: device context
///
public required init(context: IMPContext) {
super.init(context: context)
kernel = IMPFunction(context: self.context, name: "kernel_adjustWB")
addFunction(kernel)
defer{
adjustment = IMPWBFilter.defaultAdjustment
}
}
public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) {
if kernel == function {
command.setBuffer(adjustmentBuffer, offset: 0, atIndex: 0)
}
}
}
| ef1a1bef5e943b1a7d291836ef2321d2 | 27.537037 | 114 | 0.633355 | false | false | false | false |
Raizlabs/ios-template | refs/heads/master | PRODUCTNAME/app/Services/API/APISerialization.swift | mit | 1 | ///
// APISerialization.swift
// PRODUCTNAME
//
// Created by LEADDEVELOPER on TODAYSDATE.
// Copyright © THISYEAR ORGANIZATION. All rights reserved.
//
import Alamofire
import Swiftilities
private func ResponseSerializer<T>(_ serializer: @escaping (Data) throws -> T) -> DataResponseSerializer<T> {
return DataResponseSerializer { _, _, data, error in
guard let data = data else {
return .failure(error ?? APIError.noData)
}
if let error = error {
do {
let knownError = try JSONDecoder.default.decode(PRODUCTNAMEError.self, from: data)
return .failure(knownError)
} catch let decodeError {
let string = String(data: data, encoding: .utf8)
Log.info("Could not decode error, falling back to generic error: \(decodeError) \(String(describing: string))")
}
if let errorDictionary = (try? JSONSerialization.jsonObject(with: data, options: [.allowFragments])) as? [String: Any] {
return .failure(PRODUCTNAMEError.unknown(errorDictionary))
}
return .failure(error)
}
do {
return .success(try serializer(data))
} catch let decodingError {
return .failure(decodingError)
}
}
}
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Void> where Endpoint.ResponseType == Payload.Empty {
return ResponseSerializer { data in
endpoint.log(data)
}
}
/// Response serializer to import JSON Object using JSONDecoder and return an object
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Endpoint.ResponseType> where Endpoint.ResponseType: Decodable {
return ResponseSerializer { data in
endpoint.log(data)
let decoder = JSONDecoder.default
return try decoder.decode(Endpoint.ResponseType.self, from: data)
}
}
| 0397d82d452cb7c9a79dc04b7118a9e0 | 38.313725 | 167 | 0.655362 | false | false | false | false |
shitoudev/v2ex | refs/heads/master | v2ex/PostDetailViewController.swift | mit | 1 | //
// PostDetailViewController.swift
// v2ex
//
// Created by zhenwen on 6/8/15.
// Copyright (c) 2015 zhenwen. All rights reserved.
//
import UIKit
import SnapKit
import TTTAttributedLabel
import v2exKit
import SnapKit
import Kanna
class PostDetailViewController: BaseViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var toolbarView: UIView!
@IBOutlet weak var toolbarHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
var postId: Int!
var postDetail: PostDetailModel! {
didSet {
self.title = (self.postDetail != nil) ? self.postDetail?.title : "加载中...."
}
}
var dataSouce: [AnyObject] = [AnyObject]()
var indexPath: NSIndexPath!
var refreshControl: UIRefreshControl!
var atTableView: AtUserTableView!
//args: NSDictionary
func allocWithRouterParams(args: NSDictionary?) -> PostDetailViewController {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("postDetailViewController") as! PostDetailViewController
viewController.hidesBottomBarWhenPushed = true
return viewController
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
self.postDetail = nil
tableView.registerNib(UINib(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: "commentCellId")
tableView.estimatedRowHeight = 90
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = defaultTableFooterView
self.refreshControl = UIRefreshControl(frame: self.tableView.bounds)
refreshControl.addTarget(self, action: #selector(refresh), forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(self.refreshControl)
reloadTableViewData(isPull: false)
let topLayer = CALayer()
topLayer.frame = CGRect(x: 0, y: 0, width: toolbarView.width, height: 0.5)
topLayer.backgroundColor = UIColor.lightGrayColor().CGColor
toolbarView.layer.addSublayer(topLayer)
let sendButton = toolbarView.viewWithTag(11) as! UIButton
sendButton.addTarget(self, action: #selector(sendButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
getTextView().delegate = self
getTextView().placeHolder = "添加评论 输入@自动匹配用户..."
getTextView().keyboardType = UIKeyboardType.Twitter
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
addObservers()
view.keyboardTriggerOffset = self.toolbarView.height;
view.addKeyboardPanningWithActionHandler { (keyboardFrameInView, opening, closing) -> Void in
self.view.layoutIfNeeded()
self.toolbarBottomConstraint.constant = self.view.height - keyboardFrameInView.origin.y
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
removeObservers()
view.removeKeyboardControl()
}
func refresh() {
reloadTableViewData(isPull: true)
}
func reloadTableViewData(isPull pull: Bool) {
// self.postId = 199762
PostDetailModel.getPostDetail(postId, completionHandler: { (detail, error) -> Void in
if error == nil {
self.dataSouce = []
self.postDetail = detail
self.dataSouce.append(self.postDetail)
self.tableView.reloadData()
// CommentModel.getCommentsFromHtml(self.postId, page: 1, completionHandler: { (obj, error) -> Void in
// if error == nil {
// self.tableView.beginUpdates()
// var indexPaths = [NSIndexPath]()
// for (index, val) in enumerate(obj) {
// self.dataSouce.append(val)
//
// let row = self.tableView.numberOfRowsInSection(0)+index
// let indexPath = NSIndexPath(forRow: row, inSection: 0)
// self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle)
// }
// self.tableView.endUpdates()
// }
//
// if isPull {
// self.refreshControl.endRefreshing()
// }
// })
let salt = "&\(self.postDetail.replies)"
CommentModel.getComments(self.postId, salt:salt, completionHandler: { (obj, error) -> Void in
if error == nil {
self.tableView.beginUpdates()
for (index, val) in obj.enumerate() {
self.dataSouce.append(val)
let row = self.tableView.numberOfRowsInSection(0)+index
let indexPath = NSIndexPath(forRow: row, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle)
}
self.tableView.endUpdates()
}
if pull {
self.refreshControl.endRefreshing()
}
})
}else{
if pull {
self.refreshControl.endRefreshing()
}
}
})
}
func postLoaded() {
tableView.reloadData()
}
// MARK: button tapped
@IBAction func userTapped(sender: AnyObject) {
pushToProfileViewController(self.postDetail.member.username)
}
func commentUserTapped(sender: AnyObject) {
let button = sender as! UIButton
let comment = dataSouce[button.tag] as! CommentModel
pushToProfileViewController(comment.member.username)
}
func pushToProfileViewController(username: String) {
if username != MemberModel.sharedMember.username {
let profileViewController = ProfileViewController().allocWithRouterParams(nil)
profileViewController.isMine = false
profileViewController.username = username
navigationController?.pushViewController(profileViewController, animated: true)
}
}
func sendButtonTapped(sender: UIButton) {
if !MemberModel.sharedMember.isLogin() {
let accountViewController = AccountViewController().allocWithRouterParams(nil)
presentViewController(UINavigationController(rootViewController: accountViewController), animated: true, completion: nil)
return
}
if getTextView().text.isEmpty {
return
}
JDStatusBarNotification.showWithStatus("提交中...", styleName: JDStatusBarStyleDark)
JDStatusBarNotification.showActivityIndicator(true, indicatorStyle: UIActivityIndicatorViewStyle.White)
// get once code
let mgr = APIManage.sharedManager
let url = APIManage.Router.Post + String(postId) // String(199762)
mgr.request(.GET, url, parameters: nil).responseString(encoding: nil) { (response) -> Void in
if response.result.isSuccess, let once = APIManage.getOnceStringFromHtmlResponse(response.result.value!) {
// submit comment
mgr.session.configuration.HTTPAdditionalHeaders?.updateValue(url, forKey: "Referer")
mgr.request(.POST, url, parameters: ["content":self.getTextView().text, "once":once]).responseString(encoding: nil, completionHandler: { (response) -> Void in
// println("args = \(self.getTextView().text + once), str = \(str)")
if response.result.isSuccess {
guard let doc = HTML(html: response.result.value!, encoding: NSUTF8StringEncoding) else {
JDStatusBarNotification.showWithStatus("数据解析失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning)
return
}
if let divProblem = doc.at_css("div[class='problem']"), liNode = divProblem.at_css("li"), problem = liNode.text {
let errorStr = problem
JDStatusBarNotification.showWithStatus(errorStr, dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning)
} else {
// success
self.submitSuccessData()
}
}else{
JDStatusBarNotification.showWithStatus("提交失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning)
}
// println("cookies___ = \(mgr.session.configuration.HTTPCookieStorage?.cookies)")
})
} else {
JDStatusBarNotification.showWithStatus("once 获取失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning)
}
}
}
func submitSuccessData() {
JDStatusBarNotification.showWithStatus("提交完成:]", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleSuccess)
let content = getTextView().text
let user = MemberModel.sharedMember
let data = ["id":0, "content":content, "created":NSDate().timeIntervalSince1970, "member":["username":user.username, "avatar_large":user.avatar_large]]
let comment = CommentModel(fromDictionary: data)
// println("comment.data = \(data)")
// update row
tableView.beginUpdates()
dataSouce.append(comment)
let row = tableView.numberOfRowsInSection(0)
let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle)
tableView.endUpdates()
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false)
getTextView().text = ""
getTextView().setNeedsDisplay()
}
// MARK: Key-value observing
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let newContentSize = change?[NSKeyValueChangeNewKey]!.CGSizeValue() {
var dy = newContentSize.height
if let oldContentSize = change?[NSKeyValueChangeOldKey]!.CGSizeValue() {
dy -= oldContentSize.height
}
toolbarHeightConstraint.constant = toolbarHeightConstraint.constant + dy
view.setNeedsUpdateConstraints()
view.layoutIfNeeded()
}
}
// MARK: Utilities
func addObservers() {
getTextView().addObserver(self, forKeyPath: "contentSize", options: [.Old, .New], context: nil)
}
func removeObservers() {
getTextView().removeObserver(self, forKeyPath: "contentSize", context: nil)
}
func getTextView() -> STTextView {
return toolbarView.viewWithTag(10) as! STTextView
}
}
// MARK: TTTAttributedLabelDelegate
extension PostDetailViewController: TTTAttributedLabelDelegate {
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
if url != nil {
if let urlStr: String = url.absoluteString {
if urlStr.hasPrefix("@") {
let username = (urlStr as NSString).substringFromIndex(1)
let profileViewController = ProfileViewController().allocWithRouterParams(nil)
profileViewController.isMine = false
profileViewController.username = username
navigationController?.pushViewController(profileViewController, animated: true)
} else {
let webViewController = WebViewController()
webViewController.loadURLWithString(url.absoluteString)
navigationController?.pushViewController(webViewController, animated: true)
}
}
}
}
}
// MARK: AtUserTableViewDelegate
extension PostDetailViewController: AtUserTableViewDelegate {
func didSelectedUser(user: MemberModel) {
getTextView().text = getTextView().text.stringByReplacingOccurrencesOfString("@" + atTableView.searchText, withString: "@" + user.username + " ", options: NSStringCompareOptions.BackwardsSearch)
atTableView?.hidden = true
}
}
// MARK: UITextViewDelegate
extension PostDetailViewController: UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
if !textView.text.isEmpty && dataSouce.count > 0 {
if textView.text.characters.last == " " {
atTableView?.hidden = true
return
}
let components = textView.text.componentsSeparatedByString(" ")
if components.count > 0 {
let atText = components.last!
let text = atText.stringByReplacingOccurrencesOfString("@", withString: "")
if atText.hasPrefix("@") && !text.isEmpty {
if atTableView == nil {
self.atTableView = AtUserTableView(frame: tableView.bounds, style: .Plain)
atTableView.atDelegate = self
view.insertSubview(atTableView, belowSubview: toolbarView)
atTableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(tableView.snp_top).offset(64)
make.left.equalTo(tableView.snp_left)
make.right.equalTo(tableView.snp_right)
make.bottom.equalTo(tableView.snp_bottom)
}
let postDetail: PostDetailModel = dataSouce.first as! PostDetailModel
var userData = [postDetail.member]
for obj in dataSouce {
if let comment = obj as? CommentModel where userData.count > 0 {
var canAdd = true
for user in userData {
if user.username == comment.member.username {
canAdd = false
}
}
if canAdd {
userData.append(comment.member)
}
}
}
atTableView.originData = userData
}
atTableView.searchText = text
atTableView.hidden = !atTableView.searchMember()
} else {
atTableView?.hidden = true
}
}
} else {
atTableView?.hidden = true
}
}
}
// MARK: UITableViewDataSource & UITableViewDelegate
extension PostDetailViewController: UITableViewDelegate, UITableViewDataSource {
// UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell: PostContentCell = tableView.dequeueReusableCellWithIdentifier("postContentCellId") as! PostContentCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.contentLabel.delegate = self
cell.updateCell(postDetail)
return cell;
} else {
let cell: CommentCell = tableView.dequeueReusableCellWithIdentifier("commentCellId") as! CommentCell
cell.contentLabel.delegate = self
let comment = dataSouce[indexPath.row] as! CommentModel
cell.updateCell(comment)
cell.avatarButton.tag = indexPath.row
cell.usernameButton.tag = indexPath.row
if !cell.isButtonAddTarget {
cell.avatarButton.addTarget(self, action: #selector(commentUserTapped(_:)), forControlEvents: .TouchUpInside)
cell.usernameButton.addTarget(self, action: #selector(commentUserTapped(_:)), forControlEvents: .TouchUpInside)
cell.isButtonAddTarget = true
}
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSouce.count > 0 ? dataSouce.count : 0
}
// UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
} | 857b53bb3b108e761e6a9c04afab7824 | 42.09901 | 202 | 0.580782 | false | false | false | false |
kipyegonmark/Tetris | refs/heads/master | Tetris/Tetris/Swiftris.swift | gpl-3.0 | 1 | //
// Swiftris.swift
// Tetris
//
// Created by Mark Kipyegon Koskei on 22/03/2016.
//
//
let NumColumns = 10
let NumRows = 20
let StartingColumn = 4
let StartingRow = 0
let PreviewColumn = 12
let PreviewRow = 1
let PointsPerLine = 10
let LevelThreshold = 1000
protocol SwiftrisDelegate {
func gameDidEnd(swiftris: Swiftris)
func gameDidBegin(swiftris: Swiftris)
func gameShapeDidLand(swiftris: Swiftris)
func gameShapeDidMove(swiftris: Swiftris)
func gameShapeDidDrop(swiftris: Swiftris)
func gameDidLevelUp(swiftris: Swiftris)
}
class Swiftris {
var blockArray:Array2D<Block>
var nextShape:Shape?
var fallingShape:Shape?
var delegate:SwiftrisDelegate?
var score = 0
var level = 1
init() {
fallingShape = nil
nextShape = nil
blockArray = Array2D<Block>(columns: NumColumns, rows: NumRows)
}
func beginGame() {
if (nextShape == nil) {
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
}
delegate?.gameDidBegin(self)
}
func newShape() -> (fallingShape:Shape?, nextShape:Shape?) {
fallingShape = nextShape
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
fallingShape?.moveTo(StartingColumn, row: StartingRow)
guard detectIllegalPlacement() == false else {
nextShape = fallingShape
nextShape!.moveTo(PreviewColumn, row: PreviewRow)
endGame()
return (nil, nil)
}
return (fallingShape, nextShape)
}
func detectIllegalPlacement() -> Bool {
guard let shape = fallingShape else {
return false
}
for block in shape.blocks {
if block.column < 0 || block.column >= NumColumns
|| block.row < 0 || block.row >= NumRows {
return true
} else if blockArray[block.column, block.row] != nil {
return true
}
}
return false
}
func dropShape() {
guard let shape = fallingShape else {
return
}
while detectIllegalPlacement() == false {
shape.lowerShapeByOneRow()
}
shape.raiseShapeByOneRow()
delegate?.gameShapeDidDrop(self)
}
func letShapeFall() {
guard let shape = fallingShape else {
return
}
shape.lowerShapeByOneRow()
if detectIllegalPlacement() {
shape.raiseShapeByOneRow()
if detectIllegalPlacement() {
endGame()
} else {
settleShape()
}
} else {
delegate?.gameShapeDidMove(self)
if detectTouch() {
settleShape()
}
}
}
func rotateShape() {
guard let shape = fallingShape else {
return
}
shape.rotateClockwise()
guard detectIllegalPlacement() == false else {
shape.rotateCounterClockwise()
return
}
delegate?.gameShapeDidMove(self)
}
func moveShapeLeft() {
guard let shape = fallingShape else {
return
}
shape.shiftLeftByOneColumn()
guard detectIllegalPlacement() == false else {
shape.shiftRightByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
func moveShapeRight() {
guard let shape = fallingShape else {
return
}
shape.shiftRightByOneColumn()
guard detectIllegalPlacement() == false else {
shape.shiftLeftByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
func settleShape() {
guard let shape = fallingShape else {
return
}
for block in shape.blocks {
blockArray[block.column, block.row] = block
}
fallingShape = nil
delegate?.gameShapeDidLand(self)
}
func detectTouch() -> Bool {
guard let shape = fallingShape else {
return false
}
for bottomBlock in shape.bottomBlocks {
if bottomBlock.row == NumRows - 1
|| blockArray[bottomBlock.column, bottomBlock.row + 1] != nil {
return true
}
}
return false
}
func endGame() {
score = 0
level = 1
delegate?.gameDidEnd(self)
}
func removeCompletedLines() -> (linesRemoved: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>) {
var removedLines = Array<Array<Block>>()
for var row = NumRows - 1; row > 0; row-- {
var rowOfBlocks = Array<Block>()
for column in 0..<NumColumns {
guard let block = blockArray[column, row] else {
continue
}
rowOfBlocks.append(block)
}
if rowOfBlocks.count == NumColumns {
removedLines.append(rowOfBlocks)
for block in rowOfBlocks {
blockArray[block.column, block.row] = nil
}
}
}
if removedLines.count == 0 {
return ([], [])
}
let pointsEarned = removedLines.count * PointsPerLine * level
score += pointsEarned
if score >= level * LevelThreshold {
level += 1
delegate?.gameDidLevelUp(self)
}
var fallenBlocks = Array<Array<Block>>()
for column in 0..<NumColumns {
var fallenBlocksArray = Array<Block>()
for var row = removedLines[0][0].row - 1; row > 0; row-- {
guard let block = blockArray[column, row] else {
continue
}
var newRow = row
while (newRow < NumRows - 1 && blockArray[column, newRow + 1] == nil) {
newRow++
}
block.row = newRow
blockArray[column, row] = nil
blockArray[column, newRow] = block
fallenBlocksArray.append(block)
}
if fallenBlocksArray.count > 0 {
fallenBlocks.append(fallenBlocksArray)
}
}
return (removedLines, fallenBlocks)
}
func removeAllBlocks() -> Array<Array<Block>> {
var allBlocks = Array<Array<Block>>()
for row in 0..<NumRows {
var rowOfBlocks = Array<Block>()
for column in 0..<NumColumns {
guard let block = blockArray[column, row] else {
continue
}
rowOfBlocks.append(block)
blockArray[column, row] = nil
}
allBlocks.append(rowOfBlocks)
}
return allBlocks
}
} | 7c425352b0d3b1734de5bcf300ced368 | 27.210526 | 107 | 0.527487 | false | false | false | false |
casd82/powerup-iOS | refs/heads/develop | Powerup/Answer.swift | gpl-2.0 | 2 | /** This struct is a data model for question/answer pair. */
struct Answer {
// Each answer has a unique ID.
var answerID: Int
// The question corresponding to this answer.
var questionID: Int
// This consists of the actual answer text.
var answerDescription: String
// Stored the ID of next question which the game transisted to if this answer is chosen.
var nextQuestionID: String
// TODO: The team should decide whether "points" should be attached to each answer.
var points: Int
// ID determining if/which OOC event should occur
var popupID: String
init(answerID: Int, questionID: Int, answerDescription: String, nextQuestionID: String, points: Int, popupID: String) {
self.answerID = answerID
self.questionID = questionID
self.answerDescription = answerDescription
self.nextQuestionID = nextQuestionID
self.points = points
self.popupID = popupID
}
}
| 927996cc8cb2795ed8dbd364dfb390fd | 32 | 123 | 0.672727 | false | false | false | false |
sjf0213/DingShan | refs/heads/master | DingshanSwift/DingshanSwift/ForumFloorData.swift | mit | 1 | //
// ForumFloorData.swift
// DingshanSwift
//
// Created by song jufeng on 15/9/9.
// Copyright (c) 2015年 song jufeng. All rights reserved.
//
import Foundation
class ForumFloorData : NSObject {
var floorId:Int = 0
var contentText:String = ""
var isLordFloor:Bool = false
var rowHeight:CGFloat = 0.0
var contentAttrString:NSAttributedString?
required override init() {
super.init()
}
init( dic : [NSObject: AnyObject]){
if let s = dic["floor_id"] as? String {
if let n = Int(s){
floorId = n
}
}else{
if let n = dic["floor_id"] as? NSNumber{
floorId = n.integerValue
}
}
if let tmp = dic["floor_content"] as? String{
contentText = tmp
}
}
func getCalculatedRowHeight() -> CGFloat
{
if (rowHeight > 0){
return rowHeight
}else {
return self.calculateRowHeight()
}
}
func calculateRowHeight() -> CGFloat
{
// 正文与图片
let widthLimit = isLordFloor ? kForumLordFloorContentWidth : kForumFollowingFloorContentWidth
let sz:CGSize = TTTAttributedLabel.sizeThatFitsAttributedString(contentAttrString, withConstraints: CGSizeMake(widthLimit, CGFloat.max), limitedToNumberOfLines: UInt.max)
rowHeight = sz.height
print("----------------calculateRowHeight= \(sz)")
return max(rowHeight, kMinForumLordFloorContentHieght)
}
} | b1c3d1eed13a1b74d9896341dba28238 | 26.105263 | 178 | 0.580311 | false | false | false | false |
WickedColdfront/Slide-iOS | refs/heads/master | Pods/reddift/reddift/Model/User.swift | apache-2.0 | 3 | //
// User.swift
// reddift
//
// Created by sonson on 2015/11/12.
// Copyright © 2015年 sonson. All rights reserved.
//
import Foundation
/**
*/
public enum UserModPermission: String {
case all
case wiki
case posts
case mail
case flair
case unknown
public init(_ value: String) {
switch value {
case "all":
self = .all
case "wiki":
self = .wiki
case "posts":
self = .posts
case "mail":
self = .mail
case "flair":
self = .flair
default:
self = .unknown
}
}
}
/**
User object
*/
public struct User {
let date: TimeInterval
let modPermissions: [UserModPermission]
let name: String
let id: String
public init(date: Double, permissions: [String]?, name: String, id: String) {
self.date = date
if let permissions = permissions {
self.modPermissions = permissions.map({UserModPermission($0)})
} else {
self.modPermissions = []
}
self.name = name
self.id = id
}
}
| 224721ca3172741b3ff78b57aed5a9c1 | 18.655172 | 81 | 0.526316 | false | false | false | false |
pusher-community/pusher-websocket-swift | refs/heads/master | Sources/ObjC/PusherClientOptions+ObjectiveC.swift | mit | 2 | import Foundation
@objc public extension PusherClientOptions {
// initializer without legacy "attemptToReturnJSONObject"
convenience init(
ocAuthMethod authMethod: OCAuthMethod,
autoReconnect: Bool = true,
ocHost host: OCPusherHost = PusherHost.defaultHost.toObjc(),
port: NSNumber? = nil,
useTLS: Bool = true,
activityTimeout: NSNumber? = nil
) {
self.init(
ocAuthMethod: authMethod,
attemptToReturnJSONObject: true,
autoReconnect: autoReconnect,
ocHost: host,
port: port,
useTLS: useTLS,
activityTimeout: activityTimeout
)
}
convenience init(
ocAuthMethod authMethod: OCAuthMethod,
attemptToReturnJSONObject: Bool = true,
autoReconnect: Bool = true,
ocHost host: OCPusherHost = PusherHost.defaultHost.toObjc(),
port: NSNumber? = nil,
useTLS: Bool = true,
activityTimeout: NSNumber? = nil
) {
self.init(
authMethod: AuthMethod.fromObjc(source: authMethod),
attemptToReturnJSONObject: attemptToReturnJSONObject,
autoReconnect: autoReconnect,
host: PusherHost.fromObjc(source: host),
port: port as? Int,
useTLS: useTLS,
activityTimeout: activityTimeout as? TimeInterval
)
}
convenience init(authMethod: OCAuthMethod) {
self.init(authMethod: AuthMethod.fromObjc(source: authMethod))
}
func setAuthMethod(authMethod: OCAuthMethod) {
self.authMethod = AuthMethod.fromObjc(source: authMethod)
}
}
| 622cfdec433365286331dda097383e96 | 30.942308 | 70 | 0.622517 | false | false | false | false |
kaojohnny/CoreStore | refs/heads/master | Sources/ObjectiveC/CSOrderBy.swift | mit | 1 | //
// CSOrderBy.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CSOrderBy
/**
The `CSOrderBy` serves as the Objective-C bridging type for `OrderBy`.
- SeeAlso: `OrderBy`
*/
@objc
public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteClause, CoreStoreObjectiveCType {
/**
The list of sort descriptors
*/
@objc
public var sortDescriptors: [NSSortDescriptor] {
return self.bridgeToSwift.sortDescriptors
}
/**
Initializes a `CSOrderBy` clause with a single sort descriptor
```
MyPersonEntity *people = [transaction
fetchAllFrom:CSFromClass([MyPersonEntity class])
fetchClauses:@[CSOrderByKey(CSSortAscending(@"fullname"))]]];
```
- parameter sortDescriptor: a `NSSortDescriptor`
*/
@objc
public convenience init(sortDescriptor: NSSortDescriptor) {
self.init(OrderBy(sortDescriptor))
}
/**
Initializes a `CSOrderBy` clause with a list of sort descriptors
```
MyPersonEntity *people = [transaction
fetchAllFrom:CSFromClass([MyPersonEntity class])
fetchClauses:@[CSOrderByKeys(CSSortAscending(@"fullname"), CSSortDescending(@"age"), nil))]]];
```
- parameter sortDescriptors: an array of `NSSortDescriptor`s
*/
@objc
public convenience init(sortDescriptors: [NSSortDescriptor]) {
self.init(OrderBy(sortDescriptors))
}
// MARK: NSObject
public override var hash: Int {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
guard let object = object as? CSOrderBy else {
return false
}
return self.bridgeToSwift == object.bridgeToSwift
}
public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)"
}
// MARK: CSFetchClause, CSQueryClause, CSDeleteClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
// MARK: CoreStoreObjectiveCType
public let bridgeToSwift: OrderBy
public init(_ swiftValue: OrderBy) {
self.bridgeToSwift = swiftValue
super.init()
}
}
// MARK: - OrderBy
extension OrderBy: CoreStoreSwiftType {
// MARK: CoreStoreSwiftType
public typealias ObjectiveCType = CSOrderBy
}
| efc60ebce7ceb416f7673cd126d9accd | 27.530303 | 111 | 0.665959 | false | false | false | false |
SuperJerry/Swift | refs/heads/master | linkedlist.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
//import UIKit
//var str = "Hello, playground"
public class Node<T: Equatable> {
var value: T
var next: Node? = nil
init(_ value: T){
self.value = value
}
}
public class Linkedlist<T: Equatable>{
var head: Node<T>? = nil
func Insertathead(value: T){
if head == nil{
self.head = Node(value)
}else{
let newNode = Node(value)
newNode.next = head
self.head = newNode
}
}
func Insertattail(value:T){
if head == nil{
self.head = Node(value)
}else{
var lastNode = head
while lastNode?.next != nil{
lastNode = lastNode?.next
}
let newNode = Node(value)
lastNode?.next = newNode
}
}
func remove(value: T){
if head != nil{
var node = head
var previousnode: Node<T>? = nil
while node?.value != value && node?.next != nil{
previousnode = node
node = node?.next
}
if node?.value == value{
if node?.next != nil{
previousnode?.next = node?.next
}else{
previousnode?.next = nil
}
}
}
}
var description : String{
var node = head
var description = "\(node!.value)"
while node?.next != nil{
node = node?.next
description += ",\(node!.value)"
}
return description
}
}
var listInt = Linkedlist<Int>()
listInt.Insertathead(20)
listInt.Insertattail(30)
listInt.Insertattail(40)
listInt.Insertathead(10)
listInt.Insertathead(0)
listInt.description
println(listInt.description)
var listStr = Linkedlist<String>()
listStr.Insertathead("B")
listStr.Insertattail("C")
listStr.Insertattail("C")
listStr.Insertattail("D")
listStr.Insertathead("A")
listStr.description
println(listStr.description)
listStr.remove("C")
println(listStr.description)
| 6f4d0f6f2b66ccfb75eea4b82e24c9e9 | 23.16092 | 60 | 0.534729 | false | false | false | false |
wildthink/BagOfTricks | refs/heads/master | BagOfTricks/ActionTrampoline.swift | mit | 1 | //
// ActionTrampoline.swift
// BagOfTricks
//
// Created by Jason Jobe on 3/17/16.
// Copyright © 2016 WildThink. All rights reserved.
//
// https://gist.githubusercontent.com/wildthink/677308084ab364044c76/raw/f713efca9ec6ca9b56c4405bd82ae33b1db98ec7/ActionTrampoline.swift
//
// Kudos (again) to Mike Ash!
// https://www.mikeash.com/pyblog/friday-qa-2015-12-25-swifty-targetaction.html
//
import Foundation
#if os(iOS)
import UIKit
public protocol UIControlActionFunctionProtocol {}
open class ActionTrampoline<T>: NSObject
{
var action: (T) -> Void
init(action: @escaping (T) -> Void) {
self.action = action
}
@objc func performAction(_ sender: UIControl) {
action(sender as! T)
}
}
let NSControlActionFunctionProtocolAssociatedObjectKey = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
extension UIControlActionFunctionProtocol where Self: UIControl
{
func addAction(_ events: UIControlEvents, _ action: @escaping (Self) -> Void) {
let trampoline = ActionTrampoline(action: action)
let call = #selector(trampoline.performAction(_:))
self.addTarget(trampoline, action: call, for: events)
objc_setAssociatedObject(self, NSControlActionFunctionProtocolAssociatedObjectKey, trampoline, .OBJC_ASSOCIATION_RETAIN)
}
func setup(_ setup: (Self) -> Void) -> Self {
setup(self)
return self
}
}
extension UIControl: UIControlActionFunctionProtocol {}
#else
import Cocoa
public protocol NSControlActionFunctionProtocol {}
public class ActionTrampoline<T>: NSObject
{
var action: T -> Void
init(action: T -> Void) {
self.action = action
}
@objc func performAction(sender: NSControl) {
action(sender as! T)
}
}
let NSControlActionFunctionProtocolAssociatedObjectKey = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
extension NSControlActionFunctionProtocol where Self: NSControl
{
func addAction(action: Self -> Void) {
let trampoline = ActionTrampoline(action: action)
self.target = trampoline
self.action = #selector(trampoline.performAction(_:))
objc_setAssociatedObject(self, NSControlActionFunctionProtocolAssociatedObjectKey, trampoline, .OBJC_ASSOCIATION_RETAIN)
}
func setup(setup: (Self) -> Void) -> Self {
setup(self)
return self
}
}
extension NSControl: NSControlActionFunctionProtocol {}
#endif
| d12cb5bde47f61f27abaa9ffcfccb8f2 | 27.451613 | 137 | 0.652683 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/Constraints/construction.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift
struct X {
var i : Int, j : Int
}
struct Y {
init (_ x : Int, _ y : Float, _ z : String) {}
}
enum Z {
case none
case char(UnicodeScalar)
case string(String)
case point(Int, Int)
init() { self = .none }
init(_ c: UnicodeScalar) { self = .char(c) }
// expected-note@-1 2 {{candidate expects value of type 'UnicodeScalar' (aka 'Unicode.Scalar') for parameter #1}}
init(_ s: String) { self = .string(s) }
// expected-note@-1 2 {{candidate expects value of type 'String' for parameter #1}}
init(_ x: Int, _ y: Int) { self = .point(x, y) }
}
enum Optional<T> { // expected-note {{'T' declared as parameter to type 'Optional'}}
case none
case value(T)
init() { self = .none }
init(_ t: T) { self = .value(t) }
}
class Base { }
class Derived : Base { }
var d : Derived
typealias Point = (x : Int, y : Int)
var hello : String = "hello";
var world : String = "world";
var i : Int
var z : Z = .none
func acceptZ(_ z: Z) {}
func acceptString(_ s: String) {}
Point(1, 2) // expected-warning {{expression of type '(x: Int, y: Int)' is unused}}
var db : Base = d
X(i: 1, j: 2) // expected-warning{{unused}}
Y(1, 2, "hello") // expected-warning{{unused}}
// Unions
Z(UnicodeScalar("a")) // expected-warning{{unused}}
Z(1, 2) // expected-warning{{unused}}
acceptZ(.none)
acceptZ(.char("a"))
acceptString("\(hello), \(world) #\(i)!")
Optional<Int>(1) // expected-warning{{unused}}
Optional(1) // expected-warning{{unused}}
_ = .none as Optional<Int>
Optional(.none) // expected-error{{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<Any>}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'none'}}
// Interpolation
_ = "\(hello), \(world) #\(i)!"
class File {
init() {
fd = 0
body = ""
}
var fd : Int32, body : String
func replPrint() {
print("File{\n fd=\(fd)\n body=\"\(body)\"\n}", terminator: "")
}
}
// Non-trivial references to metatypes.
struct Foo {
struct Inner { }
}
extension Foo {
func getInner() -> Inner {
return Inner()
}
}
// Downcasting
var b : Base
_ = b as! Derived
// Construction doesn't permit conversion.
// NOTE: Int and other integer-literal convertible types
// are special cased in the library.
Int(i) // expected-warning{{unused}}
_ = i as Int
Z(z) // expected-error{{no exact matches in call to initializer}}
Z.init(z) // expected-error {{no exact matches in call to initializer}}
_ = z as Z
// Construction from inouts.
struct FooRef { }
struct BarRef {
init(x: inout FooRef) {}
init(x: inout Int) {}
}
var f = FooRef()
var x = 0
BarRef(x: &f) // expected-warning{{unused}}
BarRef(x: &x) // expected-warning{{unused}}
// Construction from a Type value not immediately resolved.
struct S1 {
init(i: Int) { }
}
struct S2 {
init(i: Int) { }
}
func getMetatype(_ i: Int) -> S1.Type { return S1.self }
func getMetatype(_ d: Double) -> S2.Type { return S2.self }
var s1 = getMetatype(1).init(i: 5)
s1 = S1(i: 5)
var s2 = getMetatype(3.14).init(i: 5)
s2 = S2(i: 5)
// rdar://problem/19254404
let i32 = Int32(123123123)
Int(i32 - 2 + 1) // expected-warning{{unused}}
// rdar://problem/19459079
let xx: UInt64 = 100
let yy = ((xx + 10) - 5) / 5
let zy = (xx + (10 - 5)) / 5
// rdar://problem/30588177
struct S3 {
init() { }
}
let s3a = S3()
extension S3 {
init?(maybe: S3) { return nil }
}
let s3b = S3(maybe: s3a)
// SR-5245 - Erroneous diagnostic - Type of expression is ambiguous without more context
class SR_5245 {
struct S {
enum E {
case e1
case e2
}
let e: [E]
}
init(s: S) {}
}
SR_5245(s: SR_5245.S(f: [.e1, .e2]))
// expected-error@-1 {{incorrect argument label in call (have 'f:', expected 'e:')}} {{22-23=e}}
// rdar://problem/34670592 - Compiler crash on heterogeneous collection literal
_ = Array([1, "hello"]) // Ok
func init_via_non_const_metatype(_ s1: S1.Type) {
_ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}}
_ = s1.init(i: 42) // ok
}
// rdar://problem/45535925 - diagnostic is attached to invalid source location
func rdar_45535925() {
struct S {
var addr: String
var port: Int
private init(addr: String, port: Int?) {
// expected-note@-1 {{'init(addr:port:)' declared here}}
self.addr = addr
self.port = port ?? 31337
}
private init(port: Int) {
self.addr = "localhost"
self.port = port
}
private func foo(_: Int) {} // expected-note {{'foo' declared here}}
private static func bar() {} // expected-note {{'bar()' declared here}}
}
_ = S(addr: "localhost", port: nil)
// expected-error@-1 {{'S' initializer is inaccessible due to 'private' protection level}}
func baz(_ s: S) {
s.foo(42)
// expected-error@-1 {{'foo' is inaccessible due to 'private' protection level}}
S.bar()
// expected-error@-1 {{'bar' is inaccessible due to 'private' protection level}}
}
}
// rdar://problem/50668864
func rdar_50668864() {
struct Foo {
init(anchors: [Int]) { // expected-note {{'init(anchors:)' declared here}}
self = .init { _ in [] } // expected-error {{trailing closure passed to parameter of type '[Int]' that does not accept a closure}}
}
}
}
// SR-10837 (rdar://problem/51442825) - init partial application regression
func sr_10837() {
struct S {
let value: Int
static func foo(_ v: Int?) {
_ = v.flatMap(self.init(value:)) // Ok
_ = v.flatMap(S.init(value:)) // Ok
_ = v.flatMap { S.init(value:)($0) } // Ok
_ = v.flatMap { self.init(value:)($0) } // Ok
}
}
class A {
init(bar: Int) {}
}
class B : A {
init(value: Int) {}
convenience init(foo: Int = 42) {
self.init(value:)(foo) // Ok
self.init(value:)
// expected-error@-1 {{partial application of 'self.init' initializer delegation is not allowed}}
}
}
class C : A {
override init(bar: Int) {
super.init(bar:)(bar) // Ok
super.init(bar:)
// expected-error@-1 {{partial application of 'super.init' initializer chain is not allowed}}
}
}
}
// To make sure that hack related to type variable bindings works as expected we need to test
// that in the following case result of a call to `reduce` maintains optionality.
func test_that_optionality_of_closure_result_is_preserved() {
struct S {}
let arr: [S?] = []
let _: [S]? = arr.reduce([], { (a: [S]?, s: S?) -> [S]? in
a.flatMap { (group: [S]) -> [S]? in s.map { group + [$0] } } // Ok
})
}
| fdf7d3cb1fb86eb529de6554dbdd9ecf | 23.988764 | 171 | 0.605665 | false | false | false | false |
mitchtreece/Bulletin | refs/heads/master | Example/Pods/Espresso/Espresso/Classes/Core/Protocols/Convertibles/BoolConvertible.swift | mit | 1 | //
// BoolConvertible.swift
// Espresso
//
// Created by Mitch Treece on 12/15/17.
//
import Foundation
/**
Protocol describing the conversion to various `Bool` representations.
*/
public protocol BoolConvertible {
/**
A boolean representation.
*/
var bool: Bool? { get }
/**
A boolean integer representation; _0 or 1_.
*/
var boolInt: Int? { get }
/**
A boolean string representation _"true" or "false"_.
*/
var boolString: String? { get }
}
extension Bool: BoolConvertible {
public static let trueString = "true"
public static let falseString = "false"
public var bool: Bool? {
return self
}
public var boolInt: Int? {
return self ? 1 : 0
}
public var boolString: String? {
return self ? Bool.trueString : Bool.falseString
}
}
extension Int: BoolConvertible {
public var bool: Bool? {
return (self <= 0) ? false : true
}
public var boolInt: Int? {
return (self <= 0) ? 0 : 1
}
public var boolString: String? {
return (self <= 0) ? Bool.falseString : Bool.trueString
}
}
extension String: BoolConvertible {
public var bool: Bool? {
guard let value = self.boolInt else { return nil }
switch value {
case 0: return false
case 1: return true
default: return nil
}
}
public var boolInt: Int? {
guard let value = self.boolString else { return nil }
switch value {
case Bool.trueString: return 1
case Bool.falseString: return 0
default: return nil
}
}
public var boolString: String? {
let value = self.lowercased()
if value == Bool.trueString || value == "1" {
return Bool.trueString
}
else if value == Bool.falseString || value == "0" {
return Bool.falseString
}
return nil
}
}
| 1225fb632ff286c6c960bebf3e3e4136 | 18.490741 | 70 | 0.528266 | false | false | false | false |
muukii/Realm-EasyBackground | refs/heads/master | Example/Pods/RealmSwift/RealmSwift/List.swift | mit | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/// :nodoc:
/// Internal class. Do not use directly.
public class ListBase: RLMListBase {
// Printable requires a description property defined in Swift (and not obj-c),
// and it has to be defined as @objc override, which can't be done in a
// generic class.
/// Returns a human-readable description of the objects contained in the List.
@objc public override var description: String {
return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
}
@objc private func descriptionWithMaxDepth(depth: UInt) -> String {
let type = "List<\(_rlmArray.objectClassName)>"
return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type
}
/// Returns the number of objects in this List.
public var count: Int { return Int(_rlmArray.count) }
}
/**
`List<T>` is the container type in Realm used to define to-many relationships.
Lists hold a single `Object` subclass (`T`) which defines the "type" of the List.
Lists can be filtered and sorted with the same predicates as `Results<T>`.
When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`.
*/
public final class List<T: Object>: ListBase {
/// Element type contained in this collection.
public typealias Element = T
// MARK: Properties
/// The Realm the objects in this List belong to, or `nil` if the List's
/// owning object does not belong to a Realm (the List is standalone).
public var realm: Realm? {
return _rlmArray.realm.map { Realm($0) }
}
/// Indicates if the List can no longer be accessed.
public var invalidated: Bool { return _rlmArray.invalidated }
// MARK: Initializers
/// Creates a `List` that holds objects of type `T`.
public override init() {
super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className()))
}
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the List.
- parameter object: The object whose index is being queried.
- returns: The index of the given object, or `nil` if the object is not in the List.
*/
public func indexOf(object: T) -> Int? {
return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self)))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicate: NSPredicate) -> Int? {
return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally
followed by a variable number of arguments.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index` on get.
Replaces the object at the given `index` on set.
- warning: You can only set an object during a write transaction.
- parameter index: The index.
- returns: The object at the given `index`.
*/
public subscript(index: Int) -> T {
get {
throwForNegativeIndex(index)
return _rlmArray[UInt(index)] as! T
}
set {
throwForNegativeIndex(index)
return _rlmArray[UInt(index)] = unsafeBitCast(newValue, RLMObject.self)
}
}
/// Returns the first object in the List, or `nil` if empty.
public var first: T? { return _rlmArray.firstObject() as! T? }
/// Returns the last object in the List, or `nil` if empty.
public var last: T? { return _rlmArray.lastObject() as! T? }
// MARK: KVC
/**
Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
- parameter key: The name of the property.
- returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
*/
public override func valueForKey(key: String) -> AnyObject? {
return _rlmArray.valueForKey(key)
}
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property.
*/
public override func setValue(value: AnyObject?, forKey key: String) {
return _rlmArray.setValue(value, forKey: key)
}
// MARK: Filtering
/**
Returns `Results` containing elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing elements that match the given predicate.
*/
public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> {
return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args)))
}
/**
Returns `Results` containing elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing elements that match the given predicate.
*/
public func filter(predicate: NSPredicate) -> Results<T> {
return Results<T>(_rlmArray.objectsWithPredicate(predicate))
}
// MARK: Sorting
/**
Returns `Results` containing elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing elements sorted by the given property.
*/
public func sorted(property: String, ascending: Bool = true) -> Results<T> {
return sorted([SortDescriptor(property: property, ascending: ascending)])
}
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> {
return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the List, or `nil` if the List is empty.
*/
public func min<U: MinMaxType>(property: String) -> U? {
return filter(NSPredicate(value: true)).min(property)
}
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the List, or `nil` if the List is empty.
*/
public func max<U: MinMaxType>(property: String) -> U? {
return filter(NSPredicate(value: true)).max(property)
}
/**
Returns the sum of the given property for objects in the List.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the List.
*/
public func sum<U: AddableType>(property: String) -> U {
return filter(NSPredicate(value: true)).sum(property)
}
/**
Returns the average of the given property for objects in the List.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the List, or `nil` if the List is empty.
*/
public func average<U: AddableType>(property: String) -> U? {
return filter(NSPredicate(value: true)).average(property)
}
// MARK: Mutation
/**
Appends the given object to the end of the List. If the object is from a
different Realm it is copied to the List's Realm.
- warning: This method can only be called during a write transaction.
- parameter object: An object.
*/
public func append(object: T) {
_rlmArray.addObject(unsafeBitCast(object, RLMObject.self))
}
/**
Appends the objects in the given sequence to the end of the List.
- warning: This method can only be called during a write transaction.
- parameter objects: A sequence of objects.
*/
public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S) {
for obj in objects {
_rlmArray.addObject(unsafeBitCast(obj, RLMObject.self))
}
}
/**
Inserts the given object at the given index.
- warning: This method can only be called during a write transaction.
- warning: Throws an exception when called with an index smaller than zero
or greater than or equal to the number of objects in the List.
- parameter object: An object.
- parameter index: The index at which to insert the object.
*/
public func insert(object: T, atIndex index: Int) {
throwForNegativeIndex(index)
_rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index))
}
/**
Removes the object at the given index from the List. Does not remove the object from the Realm.
- warning: This method can only be called during a write transaction.
- warning: Throws an exception when called with an index smaller than zero
or greater than or equal to the number of objects in the List.
- parameter index: The index at which to remove the object.
*/
public func removeAtIndex(index: Int) {
throwForNegativeIndex(index)
_rlmArray.removeObjectAtIndex(UInt(index))
}
/**
Removes the last object in the List. Does not remove the object from the Realm.
- warning: This method can only be called during a write transaction.
*/
public func removeLast() {
_rlmArray.removeLastObject()
}
/**
Removes all objects from the List. Does not remove the objects from the Realm.
- warning: This method can only be called during a write transaction.
*/
public func removeAll() {
_rlmArray.removeAllObjects()
}
/**
Replaces an object at the given index with a new object.
- warning: This method can only be called during a write transaction.
- warning: Throws an exception when called with an index smaller than zero
or greater than or equal to the number of objects in the List.
- parameter index: The index of the object to be replaced.
- parameter object: An object to replace at the specified index.
*/
public func replace(index: Int, object: T) {
throwForNegativeIndex(index)
_rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self))
}
/**
Moves the object at the given source index to the given destination index.
- warning: This method can only be called during a write transaction.
- warning: Throws an exception when called with an index smaller than zero or greater than
or equal to the number of objects in the List.
- parameter from: The index of the object to be moved.
- parameter to: index to which the object at `from` should be moved.
*/
public func move(from from: Int, to: Int) { // swiftlint:disable:this variable_name
throwForNegativeIndex(from)
throwForNegativeIndex(to)
_rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to))
}
/**
Exchanges the objects in the List at given indexes.
- warning: Throws an exception when either index exceeds the bounds of the List.
- warning: This method can only be called during a write transaction.
- parameter index1: The index of the object with which to replace the object at index `index2`.
- parameter index2: The index of the object with which to replace the object at index `index1`.
*/
public func swap(index1: Int, _ index2: Int) {
throwForNegativeIndex(index1, parameterName: "index1")
throwForNegativeIndex(index2, parameterName: "index2")
_rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2))
}
// MARK: Notifications
/**
Register a block to be called each time the List changes.
The block will be asynchronously called with the initial list, and then
called again after each write transaction which changes the list or any of
the items in the list. You must retain the returned token for as long as
you want the results to continue to be sent to the block. To stop receiving
updates, call stop() on the token.
- parameter block: The block to be called each time the list changes.
- returns: A token which must be held for as long as you want notifications to be delivered.
*/
public func addNotificationBlock(block: (List<T>) -> ()) -> NotificationToken {
return _rlmArray.addNotificationBlock { _, _ in block(self) }
}
}
extension List: RealmCollectionType, RangeReplaceableCollectionType {
// MARK: Sequence Support
/// Returns a `GeneratorOf<T>` that yields successive elements in the List.
public func generate() -> RLMGenerator<T> {
return RLMGenerator(collection: _rlmArray)
}
// MARK: RangeReplaceableCollection Support
/**
Replace the given `subRange` of elements with `newElements`.
- parameter subRange: The range of elements to be replaced.
- parameter newElements: The new elements to be inserted into the List.
*/
public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>,
with newElements: C) {
for _ in subRange {
removeAtIndex(subRange.startIndex)
}
for x in newElements.reverse() {
insert(x, atIndex: subRange.startIndex)
}
}
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
/// :nodoc:
public func _addNotificationBlock(block: (AnyRealmCollection<T>?, NSError?) -> ()) -> NotificationToken {
let anyCollection = AnyRealmCollection(self)
return _rlmArray.addNotificationBlock { _, _ in block(anyCollection, nil) }
}
}
| 78cc8e8f1c2a4dd520697a2bb07d8645 | 36.142539 | 120 | 0.672243 | false | false | false | false |
eggswift/pull-to-refresh | refs/heads/master | Sources/Animator/ESRefreshHeaderAnimator.swift | mit | 1 | //
// ESRefreshHeaderView.swift
//
// Created by egg swift on 16/4/7.
// Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh)
// Icon from http://www.iconfont.cn
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import QuartzCore
import UIKit
open class ESRefreshHeaderAnimator: UIView, ESRefreshProtocol, ESRefreshAnimatorProtocol, ESRefreshImpactProtocol {
open var pullToRefreshDescription = NSLocalizedString("Pull to refresh", comment: "") {
didSet {
if pullToRefreshDescription != oldValue {
titleLabel.text = pullToRefreshDescription;
}
}
}
open var releaseToRefreshDescription = NSLocalizedString("Release to refresh", comment: "")
open var loadingDescription = NSLocalizedString("Loading...", comment: "")
open var view: UIView { return self }
open var insets: UIEdgeInsets = UIEdgeInsets.zero
open var trigger: CGFloat = 60.0
open var executeIncremental: CGFloat = 60.0
open var state: ESRefreshViewState = .pullToRefresh
fileprivate let imageView: UIImageView = {
let imageView = UIImageView.init()
let frameworkBundle = Bundle(for: ESRefreshAnimator.self)
if /* CocoaPods static */ let path = frameworkBundle.path(forResource: "ESPullToRefresh", ofType: "bundle"),let bundle = Bundle(path: path) {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
}else if /* Carthage */ let bundle = Bundle.init(identifier: "com.eggswift.ESPullToRefresh") {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
} else if /* CocoaPods */ let bundle = Bundle.init(identifier: "org.cocoapods.ESPullToRefresh") {
imageView.image = UIImage(named: "ESPullToRefresh.bundle/icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
} else /* Manual */ {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow")
}
return imageView
}()
fileprivate let titleLabel: UILabel = {
let label = UILabel.init(frame: CGRect.zero)
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.init(white: 0.625, alpha: 1.0)
label.textAlignment = .left
return label
}()
fileprivate let indicatorView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView.init(style: .gray)
indicatorView.isHidden = true
return indicatorView
}()
public override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = pullToRefreshDescription
self.addSubview(imageView)
self.addSubview(titleLabel)
self.addSubview(indicatorView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func refreshAnimationBegin(view: ESRefreshComponent) {
indicatorView.startAnimating()
indicatorView.isHidden = false
imageView.isHidden = true
titleLabel.text = loadingDescription
imageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
}
open func refreshAnimationEnd(view: ESRefreshComponent) {
indicatorView.stopAnimating()
indicatorView.isHidden = true
imageView.isHidden = false
titleLabel.text = pullToRefreshDescription
imageView.transform = CGAffineTransform.identity
}
open func refresh(view: ESRefreshComponent, progressDidChange progress: CGFloat) {
// Do nothing
}
open func refresh(view: ESRefreshComponent, stateDidChange state: ESRefreshViewState) {
guard self.state != state else {
return
}
self.state = state
switch state {
case .refreshing, .autoRefreshing:
titleLabel.text = loadingDescription
self.setNeedsLayout()
break
case .releaseToRefresh:
titleLabel.text = releaseToRefreshDescription
self.setNeedsLayout()
self.impact()
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions(), animations: {
[weak self] in
self?.imageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
}) { (animated) in }
break
case .pullToRefresh:
titleLabel.text = pullToRefreshDescription
self.setNeedsLayout()
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions(), animations: {
[weak self] in
self?.imageView.transform = CGAffineTransform.identity
}) { (animated) in }
break
default:
break
}
}
open override func layoutSubviews() {
super.layoutSubviews()
let s = self.bounds.size
let w = s.width
let h = s.height
UIView.performWithoutAnimation {
titleLabel.sizeToFit()
titleLabel.center = CGPoint.init(x: w / 2.0, y: h / 2.0)
indicatorView.center = CGPoint.init(x: titleLabel.frame.origin.x - 16.0, y: h / 2.0)
imageView.frame = CGRect.init(x: titleLabel.frame.origin.x - 28.0, y: (h - 18.0) / 2.0, width: 18.0, height: 18.0)
}
}
}
| 84cb6b565334790c50832976ae795b97 | 40.649682 | 149 | 0.655146 | false | false | false | false |
inacioferrarini/York | refs/heads/master | Example/Tests/York/DataSyncRules/DataSyncHourlyRulesTests.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import XCTest
import York
class DataSyncHourlyRulesTests: XCTestCase {
// MARK: - Supporting Methods
func createRules() -> DataSyncRules {
let coreDataStack = TestUtil().appContext().coreDataStack
return DataSyncRules(coreDataStack: coreDataStack)
}
// MARK: - Tests
func test_nonExistingHourlyRule_mustReturnFalse() {
let ruleName = TestUtil().randomString()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.hourly(12))
let result = rules.shouldPerformSyncRule("NonExistingRule", atDate: Date())
XCTAssertEqual(result, false, "Execution of a non-existing hourly rule is expected to fail.")
}
func test_nonExistingHourlyRule_update_doesNotcrash() {
let ruleName = TestUtil().randomString()
let rules = self.createRules()
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: Date())
}
func test_existingHourlyRuleHistory_update_doesNotcrash() {
let ruleName = TestUtil().randomString()
let rules = self.createRules()
let context = rules.coreDataStack.managedObjectContext
_ = EntitySyncHistory.entityAutoSyncHistoryByName(ruleName, lastExecutionDate: Date(), inManagedObjectContext: context)
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: Date())
}
func test_updatingExistingHourlyRule_doesNotCrash() {
let ruleName = TestUtil().randomString()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.hourly(12))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: Date())
}
func test_existingHourlyRuleWithoutLastExecutionDate_mustReturnTrue() {
let ruleName = TestUtil().randomString()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.hourly(12))
let result = rules.shouldPerformSyncRule(ruleName, atDate: Date())
XCTAssertEqual(result, true, "Execution of an existing hourly rule without last execution date is exected to succeeded.")
}
func test_existingHourlyRule_withDaysEquals3AndlastExecutionDateEquals3_mustReturnTrue() {
let ruleName = TestUtil().randomString()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let lastExecutionDate = formatter.date(from: "2015-03-23T01:20:20")!
let executionDate = formatter.date(from: "2015-03-26T12:20:20")!
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.hourly(12))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: lastExecutionDate)
let result = rules.shouldPerformSyncRule(ruleName, atDate: executionDate)
XCTAssertEqual(result, true)
}
func test_existingHourlyRule_withDaysEqual32AndlastExecutionDateEquals2_mustReturnFalse() {
let ruleName = TestUtil().randomString()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let lastExecutionDate = formatter.date(from: "2015-03-23T01:20:20")!
let executionDate = formatter.date(from: "2015-03-25T13:20:20")!
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.hourly(12))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: lastExecutionDate)
let result = rules.shouldPerformSyncRule(ruleName, atDate: executionDate)
XCTAssertEqual(result, true)
}
}
| c0824042dcb8695cedbd0df93597b54b | 43.448598 | 129 | 0.712574 | false | true | false | false |
OscarSwanros/swift | refs/heads/master | test/Prototypes/PatternMatching.swift | apache-2.0 | 3 | //===--- PatternMatching.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//===--- Niceties ---------------------------------------------------------===//
extension Collection {
func index(_ d: IndexDistance) -> Index {
return index(startIndex, offsetBy: d)
}
func offset(of i: Index) -> IndexDistance {
return distance(from: startIndex, to: i)
}
}
//===--- Niceties ---------------------------------------------------------===//
enum MatchResult<Index: Comparable, MatchData> {
case found(end: Index, data: MatchData)
case notFound(resumeAt: Index?)
}
protocol Pattern {
associatedtype Element : Equatable
associatedtype Index : Comparable
associatedtype MatchData = ()
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
}
extension Pattern {
func found<C: Collection>(in c: C) -> (extent: Range<Index>, data: MatchData)?
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var i = c.startIndex
while i != c.endIndex {
let m = self.matched(atStartOf: c[i..<c.endIndex])
switch m {
case .found(let end, let data):
return (extent: i..<end, data: data)
case .notFound(let j):
i = j ?? c.index(after: i)
}
}
return nil
}
}
// FIXME: Using this matcher for found(in:) has worst-case performance
// O(pattern.count * c.count).
//
// Also implement one or more of
// KMP/Boyer-Moore[-Galil]/Sustik-Moore/Z-algorithm which run in O(pattern.count
// + c.count)
struct LiteralMatch<T: Collection, Index: Comparable> : Pattern
where T.Element : Equatable {
typealias Element = T.Element
init(_ pattern: T) { self.pattern = pattern }
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var i = c.startIndex
for p in pattern {
if i == c.endIndex || c[i] != p {
return .notFound(resumeAt: nil)
}
i = c.index(after: i)
}
return .found(end: i, data: ())
}
fileprivate let pattern: T
}
struct MatchAnyOne<T : Equatable, Index : Comparable> : Pattern {
typealias Element = T
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
return c.isEmpty
? .notFound(resumeAt: c.endIndex)
: .found(end: c.index(after: c.startIndex), data: ())
}
}
extension MatchAnyOne : CustomStringConvertible {
var description: String { return "." }
}
enum MatchAny {}
var __ : MatchAny.Type { return MatchAny.self }
prefix func % <
T : Equatable, Index : Comparable
>(_: MatchAny.Type) -> MatchAnyOne<T,Index> {
return MatchAnyOne()
}
/// A matcher for two other matchers in sequence.
struct ConsecutiveMatches<M0: Pattern, M1: Pattern> : Pattern
where M0.Element == M1.Element, M0.Index == M1.Index {
init(_ m0: M0, _ m1: M1) { self.matchers = (m0, m1) }
fileprivate let matchers: (M0, M1)
typealias Element = M0.Element
typealias Index = M0.Index
typealias MatchData = (midPoint: M0.Index, data: (M0.MatchData, M1.MatchData))
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var src0 = c[c.startIndex..<c.endIndex]
while true {
switch matchers.0.matched(atStartOf: src0) {
case .found(let end0, let data0):
switch matchers.1.matched(atStartOf: c[end0..<c.endIndex]) {
case .found(let end1, let data1):
return .found(end: end1, data: (midPoint: end0, data: (data0, data1)))
case .notFound(_):
if src0.isEmpty {
// I don't think we can know anything interesting about where to
// begin searching again, because there's no communication between
// the two matchers that would allow it.
return .notFound(resumeAt: nil)
}
// backtrack
src0 = src0.dropLast()
}
case .notFound(let j):
return .notFound(resumeAt: j)
}
}
}
}
extension ConsecutiveMatches : CustomStringConvertible {
var description: String { return "(\(matchers.0))(\(matchers.1))" }
}
struct RepeatMatch<M0: Pattern> : Pattern {
typealias Element = M0.Element
typealias MatchData = [(end: M0.Index, data: M0.MatchData)]
let singlePattern: M0
var repeatLimits: ClosedRange<Int>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<M0.Index, MatchData>
where C.Index == M0.Index, C.Element == M0.Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var lastEnd = c.startIndex
var rest = c.dropFirst(0)
var data: MatchData = []
searchLoop:
while !rest.isEmpty {
switch singlePattern.matched(atStartOf: rest) {
case .found(let x):
data.append(x)
lastEnd = x.end
if data.count == repeatLimits.upperBound { break }
rest = rest[x.end..<rest.endIndex]
case .notFound(let r):
if !repeatLimits.contains(data.count) {
return .notFound(resumeAt: r)
}
break searchLoop
}
}
return .found(end: lastEnd, data: data)
}
}
extension RepeatMatch : CustomStringConvertible {
var description: String {
let suffix: String
switch (repeatLimits.lowerBound, repeatLimits.upperBound) {
case (0, Int.max):
suffix = "*"
case (1, Int.max):
suffix = "+"
case (let l, Int.max):
suffix = "{\(l)...}"
default:
suffix = "\(repeatLimits)"
}
return "(\(singlePattern))\(suffix)"
}
}
enum OneOf<A, B> {
case a(A)
case b(B)
}
extension OneOf : CustomStringConvertible {
var description: String {
switch self {
case .a(let x):
return "\(x)"
case .b(let x):
return "\(x)"
}
}
}
struct MatchOneOf<M0: Pattern, M1: Pattern> : Pattern
where M0.Element == M1.Element, M0.Index == M1.Index {
init(_ m0: M0, _ m1: M1) { self.matchers = (m0, m1) }
fileprivate let matchers: (M0, M1)
typealias Element = M0.Element
typealias Index = M0.Index
typealias MatchData = OneOf<M0.MatchData,M1.MatchData>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
switch matchers.0.matched(atStartOf: c) {
case .found(let end, let data):
return .found(end: end, data: .a(data))
case .notFound(let r0):
switch matchers.1.matched(atStartOf: c) {
case .found(let end, let data):
return .found(end: end, data: .b(data))
case .notFound(let r1):
if let s0 = r0, let s1 = r1 {
return .notFound(resumeAt: min(s0, s1))
}
return .notFound(resumeAt: nil)
}
}
}
}
extension MatchOneOf : CustomStringConvertible {
var description: String { return "\(matchers.0)|\(matchers.1)" }
}
infix operator .. : AdditionPrecedence
postfix operator *
postfix operator +
func .. <M0: Pattern, M1: Pattern>(m0: M0, m1: M1) -> ConsecutiveMatches<M0,M1> {
return ConsecutiveMatches(m0, m1)
}
postfix func * <M: Pattern>(m: M) -> RepeatMatch<M> {
return RepeatMatch(singlePattern: m, repeatLimits: 0...Int.max)
}
postfix func + <M: Pattern>(m: M) -> RepeatMatch<M> {
return RepeatMatch(singlePattern: m, repeatLimits: 1...Int.max)
}
func | <M0: Pattern, M1: Pattern>(m0: M0, m1: M1) -> MatchOneOf<M0,M1> {
return MatchOneOf(m0, m1)
}
//===--- Just for testing -------------------------------------------------===//
struct MatchStaticString : Pattern {
typealias Element = UTF8.CodeUnit
typealias Buffer = UnsafeBufferPointer<Element>
typealias Index = Buffer.Index
let content: StaticString
init(_ x: StaticString) { content = x }
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
return content.withUTF8Buffer {
LiteralMatch<Buffer, Index>($0).matched(atStartOf: c)
}
}
}
extension MatchStaticString : CustomStringConvertible {
var description: String { return String(describing: content) }
}
// A way to force string literals to be interpreted as StaticString
prefix operator %
extension StaticString {
static prefix func %(x: StaticString) -> MatchStaticString {
return MatchStaticString(x)
}
}
extension Collection where Iterator.Element == UTF8.CodeUnit {
var u8str : String {
var a = Array<UTF8.CodeUnit>()
a.reserveCapacity(numericCast(count) + 1)
a.append(contentsOf: self)
a.append(0)
return String(reflecting: String(cString: a))
}
}
extension Pattern where Element == UTF8.CodeUnit {
func searchTest<C: Collection>(
in c: C,
format: (MatchData)->String = { String(reflecting: $0) })
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection {
print("searching for /\(self)/ in \(c.u8str)...", terminator: "")
if let (extent, data) = self.found(in: c) {
print(
"\nfound at",
"\(c.offset(of: extent.lowerBound)..<c.offset(of: extent.upperBound)):",
c[extent].u8str,
MatchData.self == Void.self ? "" : "\ndata: \(format(data))")
}
else {
print("NOT FOUND")
}
print()
}
}
//===--- Just for testing -------------------------------------------------===//
//===--- Tests ------------------------------------------------------------===//
let source = Array("the quick brown fox jumps over the lazy dog".utf8)
let source2 = Array("hack hack cough cough cough spork".utf8)
(%"fox").searchTest(in: source)
(%"fog").searchTest(in: source)
(%"fox" .. %" box").searchTest(in: source)
(%"fox" .. %" jump").searchTest(in: source)
(%"cough")*.searchTest(in: source2)
(%"sneeze")+.searchTest(in: source2)
(%"hack ")*.searchTest(in: source2)
(%"cough ")+.searchTest(in: source2)
let fancyPattern
= %"quick "..((%"brown" | %"black" | %"fox" | %"chicken") .. %" ")+
.. (%__)
fancyPattern.searchTest(in: source)
//===--- Parsing pairs ----------------------------------------------------===//
// The beginnings of what it will take to wrap and indent m.data in the end of
// the last test, to make it readable.
struct PairedStructure<I: Comparable> {
let bounds: Range<I>
let subStructure: [PairedStructure<I>]
}
struct Paired<T: Hashable, I: Comparable> : Pattern {
typealias Element = T
typealias Index = I
typealias MatchData = PairedStructure<I>
let pairs: Dictionary<T,T>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
guard let closer = c.first.flatMap({ pairs[$0] }) else {
return .notFound(resumeAt: nil)
}
var subStructure: [PairedStructure<I>] = []
var i = c.index(after: c.startIndex)
var resumption: Index? = nil
while i != c.endIndex {
if let m = self.found(in: c[i..<c.endIndex]) {
i = m.extent.upperBound
subStructure.append(m.data)
resumption = resumption ?? i
}
else {
let nextI = c.index(after: i)
if c[i] == closer {
return .found(
end: nextI,
data: PairedStructure(
bounds: c.startIndex..<nextI, subStructure: subStructure))
}
i = nextI
}
}
return .notFound(resumeAt: resumption)
}
}
// Local Variables:
// swift-syntax-check-fn: swift-syntax-check-single-file
// End:
| 9af582b95fb5e3577f20fb6ec8a1ade1 | 29.622912 | 81 | 0.620217 | false | false | false | false |
Nykho/Swifternalization | refs/heads/master | Pods/Swifternalization/Swifternalization/InequalitySign.swift | apache-2.0 | 5 | //
// InequalitySign.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Defines inequality signs used by inquality and inequality extended expressions.
*/
enum InequalitySign: String {
/**
Less than a value.
*/
case LessThan = "<"
/**
Less than or equal a value.
*/
case LessThanOrEqual = "<="
/**
Equal a value.
*/
case Equal = "="
/**
Greater than or equal a value.
*/
case GreaterThanOrEqual = ">="
/**
Greater than a value.
*/
case GreaterThan = ">"
/**
Inverts enum.
*/
func invert() -> InequalitySign {
switch self {
case .LessThan: return .GreaterThan
case .LessThanOrEqual: return .GreaterThanOrEqual
case .Equal: return .Equal
case .GreaterThanOrEqual: return .LessThanOrEqual
case .GreaterThan: return .LessThan
}
}
} | f03a060610440b5d01b1c0ffcdc05e94 | 18.634615 | 79 | 0.576471 | false | false | false | false |
123kyky/SteamReader | refs/heads/master | SteamReader/SteamReader/View/NewsItemHeaderView.swift | mit | 1 | //
// NewsItemHeader.swift
// SteamReader
//
// Created by Kyle Roberts on 4/29/16.
// Copyright © 2016 Kyle Roberts. All rights reserved.
//
import UIKit
class NewsItemHeaderView: UIView {
@IBOutlet var view: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var feedLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var previewLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
importView()
}
init() {
super.init(frame: CGRectZero)
importView()
}
func importView() {
NSBundle.mainBundle().loadNibNamed("NewsItemHeaderView", owner: self, options: nil)
addSubview(view)
view.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
}
func configure(newsItem: NewsItem?) {
if newsItem == nil { return }
let dateFormatter = DateFormatter()
// TODO: Move somewhere else
var htmlAttributes: NSAttributedString? {
guard
let data = newsItem!.contents!.dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
titleLabel.text = newsItem!.title
feedLabel.text = newsItem!.feedLabel
authorLabel.text = newsItem!.author
dateLabel.text = dateFormatter.stringFromDate(newsItem!.date!)
previewLabel.text = htmlAttributes?.string ?? ""
}
}
class NewsItemHeaderCell: UITableViewCell {
var newsItemView: NewsItemHeaderView?
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
newsItemView = NewsItemHeaderView()
contentView.addSubview(newsItemView!)
newsItemView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 62596d9a09f43fc39dae70ea19c5f8be | 29.216867 | 207 | 0.622408 | false | false | false | false |
itjhDev/HttpSwift2.0 | refs/heads/master | HttpSwift2.0/HttpSwift.swift | mit | 1 | // HttpSwift.swift
// HttpSwift2.0
//
// Created by SongLijun on 15/7/30.
// Copyright © 2015年 SongLijun. All rights reserved.
//
import Foundation
extension String {
var nsdata: NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding)!
}
}
/*
Swift2.0 网络请求封装
*/
class HttpSwift {
static func request(method: String, url: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void){
let manager = HttpSwiftManager(url: url, method: method, params: params, callback: callback)
manager.fire()
}
/*get请求,不带参数*/
static func get(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "GET", callback: callback)
manager.fire()
}
/*get请求,带参数*/
static func get(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "GET", params: params, callback: callback)
manager.fire()
}
/*POST请求,不带参数*/
static func post(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "POST", callback: callback)
manager.fire()
}
/*POST请求,带参数*/
static func post(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "POST", params: params, callback: callback)
manager.fire()
}
/*PUT请求,不带参数*/
static func put(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "PUT", callback: callback)
manager.fire()
}
/*PUT请求,带参数*/
static func put(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "PUT", params: params, callback: callback)
manager.fire()
}
/*DELETE请求,带参数*/
static func delete(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
let manager = HttpSwiftManager(url: url, method: "DELETE", params: params, callback: callback)
manager.fire()
}
}
/*扩展*/
class HttpSwiftManager {
let method: String!
let params: Dictionary<String, AnyObject>
let callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void
var session = NSURLSession.sharedSession()
let url: String!
var request: NSMutableURLRequest!
var task: NSURLSessionTask!
/*带参数 构造器*/
init(url: String, method: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) {
self.url = url
self.request = NSMutableURLRequest(URL: NSURL(string: url)!)
self.method = method
self.params = params
self.callback = callback
}
func buildRequest() {
if self.method == "GET" && self.params.count > 0 {
self.request = NSMutableURLRequest(URL: NSURL(string: url + "?" + buildParams(self.params))!)
}
request.HTTPMethod = self.method
if self.params.count > 0 {
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
}
func buildBody() {
if self.params.count > 0 && self.method != "GET" {
request.HTTPBody = buildParams(self.params).nsdata
}
}
func fireTask() {
task = session.dataTaskWithRequest(request,completionHandler: { (data, response, error) -> Void in
self.callback(data: NSString(data: data!, encoding: NSUTF8StringEncoding), response: response, error: error)
})
task.resume()
}
//借用 Alamofire 函数
func buildParams(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sort() {
let value: AnyObject! = parameters[key]
//拼接url
components += self.queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)", value)
}
} else {
components.appendContentsOf([(escape(key), escape("\(value)"))])
}
return components
}
func queryCarComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryCarComponents("\(key)", value)
}
} else {
components.appendContentsOf([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
func fire() {
buildRequest()
buildBody()
fireTask()
}
}
| 9aa83b10c6da1d77fdfdd2d35620de6d | 33.827027 | 206 | 0.596151 | false | false | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/DevirtualizeProtocolComposition.swift | apache-2.0 | 10 | //===--- DevirtualizeProtocolComposition.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks = [
BenchmarkInfo(name: "DevirtualizeProtocolComposition", runFunction: run_DevirtualizeProtocolComposition, tags: [.validation, .api]),
]
protocol Pingable { func ping() -> Int; func pong() -> Int}
public class Game<T> {
func length() -> Int { return 10 }
}
public class PingPong: Game<String> { }
extension PingPong : Pingable {
func ping() -> Int { return 1 }
func pong() -> Int { return 2 }
}
func playGame<T>(_ x: Game<T> & Pingable) -> Int {
var sum = 0
for _ in 0..<x.length() {
sum += x.ping() + x.pong()
}
return sum
}
@inline(never)
public func run_DevirtualizeProtocolComposition(n: Int) {
for _ in 0..<n * 20_000 {
blackHole(playGame(PingPong()))
}
}
| 6226f4e6552c99c39d1bc7270ea6a3fe | 27.288889 | 134 | 0.612726 | false | false | false | false |
danielsaidi/iExtra | refs/heads/master | iExtraTests/Files/AppFileManagerDefaultTests.swift | mit | 1 | //
// AppFileManagerDefaultTests.swift
// iExtra
//
// Created by Daniel Saidi on 2016-12-19.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import iExtra
class AppFileManagerDefaultTests: QuickSpec {
override func spec() {
describe("default global file manager") {
var manager = AppFileManagerDefault()
let directory = FileManager.SearchPathDirectory.documentDirectory
let directoryUrl = FileManager.default.urls(for: directory, in: .userDomainMask).last!
let fileNames = ["file1", "file2"]
func createFiles() {
fileNames.forEach { _ = manager.createFile(at: url(for: $0), contents: nil) }
}
func createFile(named name: String, contents: Data?) -> Bool {
return manager.createFile(at: url(for: name), contents: contents)
}
func url(for fileName: String) -> URL {
return directoryUrl.appendingPathComponent(fileName)
}
afterEach {
fileNames.forEach { _ = manager.removeFile(at: url(for: $0)) }
}
context("document folder url") {
it("is resolved for test simulator") {
let simulatorPattern = "Library/Developer/CoreSimulator/Devices"
let simulatorMatch = directoryUrl.path.contains(simulatorPattern)
let devicePattern = "/var/mobile/Containers"
let deviceMatch = directoryUrl.path.contains(devicePattern)
let match = simulatorMatch || deviceMatch
expect(match).to(beTrue())
}
}
context("when creating files") {
it("can create empty file") {
let name = "file1"
let didCreate = createFile(named: name, contents: nil)
expect(didCreate).to(beTrue())
}
it("can create non-empty file") {
let name = "file1"
let didCreate = createFile(named: name, contents: Data())
expect(didCreate).to(beTrue())
}
}
context("when checking if files exists") {
it("finds existing file") {
createFiles()
let exists = manager.fileExists(at: url(for: "file1"))
expect(exists).to(beTrue())
}
it("does not find non-existing file") {
let exists = manager.fileExists(at: url(for: "file1"))
expect(exists).to(beFalse())
}
}
context("when getting attributes of file") {
it("returns nil if file does not exist") {
let url = URL(string: "file:///foo/bar")!
let attributes = manager.getAttributesForFile(at: url)
expect(attributes).to(beNil())
}
it("returns attributes if file exists") {
createFiles()
let attributes = manager.getAttributesForFile(at: url(for: "file1"))
expect(attributes).toNot(beNil())
}
it("returns valid attributes if file exists") {
createFiles()
let attributes = manager.getAttributesForFile(at: url(for: "file1"))!
let attribute = attributes[FileAttributeKey.size] as? NSNumber
expect(attribute).to(equal(0))
}
}
context("when getting content of folder") {
it("returns urls for existing files") {
createFiles()
let urls = manager.getContentsOfDirectory(at: directoryUrl)
let fileNames = urls.map { $0.lastPathComponent }
expect(fileNames).to(contain("file1"))
expect(fileNames).to(contain("file2"))
}
it("returns no urls for no existing files") {
let urls = manager.getContentsOfDirectory(at: directoryUrl)
let fileNames = urls.map { $0.lastPathComponent }
expect(fileNames).toNot(contain("file1"))
expect(fileNames).toNot(contain("file2"))
}
}
context("when getting size of file") {
it("returns nil if file does not exist") {
let url = URL(string: "file:///foo/bar")!
let size = manager.getSizeOfFile(at: url)
expect(size).to(beNil())
}
it("returns zero size if empty file exists") {
createFiles()
let size = manager.getSizeOfFile(at: url(for: "file1"))
expect(size).to(equal(0))
}
it("returns non-zero size if empty file exists") {
let content = "content".data(using: .utf8)
_ = createFile(named: "file1", contents: content)
let size = manager.getSizeOfFile(at: url(for: "file1"))
expect(size).to(equal(7))
}
}
context("when removing file") {
it("can remove existing file") {
createFiles()
let didRemove = manager.removeFile(at: url(for: "file1"))
expect(didRemove).to(beTrue())
}
it("can not remove non-existing file") {
let didRemove = manager.removeFile(at: url(for: "file1"))
expect(didRemove).to(beFalse())
}
}
}
}
}
| 8d1ba6dc6ccc7bbd88e74df78ff442d0 | 37.353293 | 98 | 0.453084 | false | false | false | false |
adad184/XXPagingScrollView | refs/heads/master | Classes/XXPagingScrollView.swift | mit | 1 | //
// XXPagingScrollView.swift
// XXPagingScrollView
//
// Created by Ralph Li on 6/10/15.
// Copyright (c) 2015 LJC. All rights reserved.
//
import UIKit
import SnapKit
public class XXPagingScrollView: UIView {
private var widthContraint:Constraint? = nil
private var heightContraint:Constraint? = nil
/// 0 means regular paging mode (as long as self)
public var pagingWidth:CGFloat = 0 {
didSet {
if pagingWidth.isZero {
widthContraint?.activate()
}
else {
widthContraint?.deactivate()
self.scrollView.snp_updateConstraints{ (make) -> Void in
make.width.equalTo(self.pagingWidth)
}
}
}
}
/// 0 means regular paging mode (as long as self)
public var pagingHeight:CGFloat = 0 {
didSet {
if pagingHeight.isZero {
heightContraint?.activate()
}
else {
heightContraint?.deactivate()
self.scrollView.snp_updateConstraints{ (make) -> Void in
make.height.equalTo(self.pagingHeight)
}
}
}
}
private class XXReachableScrollView:UIScrollView {
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return true
}
}
public lazy var scrollView:UIScrollView! = {
var v = XXReachableScrollView()
v.clipsToBounds = false
v.pagingEnabled = true
v.showsVerticalScrollIndicator = false
v.showsHorizontalScrollIndicator = false
return v
}()
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setup()
}
private func setup() {
self.addSubview(self.scrollView)
self.scrollView.snp_makeConstraints { (make) -> Void in
make.center.equalTo(self)
make.width.equalTo(self.pagingWidth).priorityLow()
make.height.equalTo(self.pagingHeight).priorityLow()
self.widthContraint = make.width.equalTo(self.snp_width).priorityHigh().constraint
self.heightContraint = make.height.equalTo(self.snp_height).priorityHigh().constraint
}
}
}
| b8c5fd05d8f008cac5cf2197684d6448 | 27.686047 | 97 | 0.57195 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.