repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hq7781/MoneyBook | Pods/ChartsRealm/ChartsRealm/Classes/Data/RealmScatterDataSet.swift | 2 | 1898 | //
// RealmScatterDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import Realm.Dynamic
open class RealmScatterDataSet: RealmLineScatterCandleRadarDataSet, IScatterChartDataSet
{
/// The size the scatter shape will have
open var scatterShapeSize = CGFloat(10.0)
/// The radius of the hole in the shape (applies to Square, Circle and Triangle)
/// **default**: 0.0
open var scatterShapeHoleRadius: CGFloat = 0.0
/// Color for the hole in the shape. Setting to `nil` will behave as transparent.
/// **default**: nil
open var scatterShapeHoleColor: NSUIColor? = nil
/// Sets the ScatterShape this DataSet should be drawn with.
/// This will search for an available IShapeRenderer and set this renderer for the DataSet
open func setScatterShape(_ shape: ScatterChartDataSet.Shape)
{
self.shapeRenderer = ScatterChartDataSet.renderer(forShape: shape)
}
/// The IShapeRenderer responsible for rendering this DataSet.
/// This can also be used to set a custom IShapeRenderer aside from the default ones.
/// **default**: `SquareShapeRenderer`
open var shapeRenderer: IShapeRenderer? = SquareShapeRenderer()
open override func initialize()
{
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmScatterDataSet
copy.scatterShapeSize = scatterShapeSize
copy.scatterShapeHoleRadius = scatterShapeHoleRadius
copy.scatterShapeHoleColor = scatterShapeHoleColor
copy.shapeRenderer = shapeRenderer
return copy
}
}
| mit | 5e6046ed8ee4b88427ae4fb3a592b294 | 30.114754 | 94 | 0.698103 | 5.047872 | false | false | false | false |
hq7781/MoneyBook | MoneyBook/Misc/Extension/Extension+CGRect.swift | 1 | 1122 | //
// Extension+CGRect.swift
// MoneyBook
//
// Created by HongQuan on 6/5/17.
// Copyright © 2017 Roan.Hong. All rights reserved.
//
import Foundation
import CoreGraphics
extension CGRect {
init(boundingCenter center: CGPoint, radius: CGFloat) {
assert(0 <= radius, "radius must be a positive value")
self = CGRect(origin: center, size: .zero).insetBy(dx: -radius, dy: -radius)
}
//MARK: - ========== extension ==========
static func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
static func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
static func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
static func CGRectZero() ->CGRect {
return CGRect.zero
}
static func CGPointZero() -> CGPoint {
return CGPoint.zero
}
static func CGSizeZero() -> CGSize {
return CGSize.zero
}
}
| mit | 9bb3b4b1e8cc278854b8756d599c9572 | 27.025 | 103 | 0.595897 | 3.933333 | false | false | false | false |
Kruks/FindViewControl | FindViewControl/FindViewControl/ObjectClasses/FindGISReqResponse/Response/FindResult.swift | 1 | 1913 | //
// FindResult.swift
//
// Create by Krutika Mac Mini on 2/8/2016
// Copyright © 2016. All rights reserved.
// Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
class FindResult: NSObject {
var formattedAddress: String!
var geometry: FindGeometry!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary) {
formattedAddress = dictionary["formatted_address"] as? String
if let geometryData = dictionary["geometry"] as? NSDictionary {
geometry = FindGeometry(fromDictionary: geometryData)
}
}
/**
* Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> NSDictionary {
let dictionary = NSMutableDictionary()
if formattedAddress != nil {
dictionary["formatted_address"] = formattedAddress
}
if geometry != nil {
dictionary["geometry"] = geometry.toDictionary()
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder) {
formattedAddress = aDecoder.decodeObject(forKey: "formatted_address") as? String
geometry = aDecoder.decodeObject(forKey: "geometry") as? FindGeometry
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encodeWithCoder(aCoder: NSCoder) {
if formattedAddress != nil {
aCoder.encode(formattedAddress, forKey: "formatted_address")
}
if geometry != nil {
aCoder.encode(geometry, forKey: "geometry")
}
}
}
| mit | e1d58a49d2308e208d30dec8660a98e5 | 28.415385 | 180 | 0.655335 | 4.966234 | false | false | false | false |
OscarSwanros/swift | stdlib/public/core/Shims.swift | 2 | 1494 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// Additions to 'SwiftShims' that can be written in Swift.
///
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@_inlineable
@_versioned
internal func _makeSwiftNSFastEnumerationState()
-> _SwiftNSFastEnumerationState {
return _SwiftNSFastEnumerationState(
state: 0, itemsPtr: nil, mutationsPtr: nil,
extra: (0, 0, 0, 0, 0))
}
/// A dummy value to be used as the target for `mutationsPtr` in fast
/// enumeration implementations.
@_versioned // FIXME(sil-serialize-all)
internal var _fastEnumerationStorageMutationsTarget: CUnsignedLong = 0
/// A dummy pointer to be used as `mutationsPtr` in fast enumeration
/// implementations.
@_inlineable // FIXME(sil-serialize-all)
public // SPI(Foundation)
var _fastEnumerationStorageMutationsPtr: UnsafeMutablePointer<CUnsignedLong> {
return UnsafeMutablePointer(
Builtin.addressof(&_fastEnumerationStorageMutationsTarget))
}
#endif
| apache-2.0 | 85da6b416f9a4836c8de3ad34ae88bb7 | 34.571429 | 80 | 0.629853 | 5.098976 | false | false | false | false |
mlgoogle/wp | wp/Model/FlowDetails.swift | 2 | 2532 | //
// FlowDetails.swift
// wp
//
// Created by macbook air on 17/1/3.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class FlowDetails: BaseModel {
dynamic var basic: Basic?
dynamic var flowdetail: Custom? //根据flow Type不同而返回不同
}
class Basic: BaseModel {
dynamic var id: Int64 = 0 //用户id
dynamic var flowId: Int64 = 0 //订单流水号
dynamic var flowType: Int32 = 0 //订单类型
dynamic var flowName: String? //订单类型名称
dynamic var inOut: Int32 = 0 //收支类型
dynamic var amount: Double = 0.0 //金额
dynamic var balance: Double = 0.0 //账户余额
dynamic var flowTime:Int64 = 0 //订单时间
dynamic var comment: String? //备注
}
class Custom: BaseModel {
//flowType = 1 入金流水时返回
dynamic var depositType: String? //入金方式
dynamic var depositName: String? //入金方式名
//flowType = 2 出金流水时返回
dynamic var bank: String? //银行
dynamic var cardNo: String? //银行卡号
dynamic var name: String? //姓名
dynamic var status: Int8 = 0 //出金状态
dynamic var withdrawAmount: Double = 0.0 //出金金额
dynamic var withdrawCharge: Double = 0.0 //出金手续费
//flowType = 3,4 建仓/平仓流水时返回
dynamic var goodsName: String? //商品名称
dynamic var buySell: Int8 = 0 //建仓方向
dynamic var positionAmount: Int32 = 0 //建仓手数
dynamic var openPrice: Double = 0.0 //建仓价格
dynamic var positionTime: Int64 = 0 //建仓时间
dynamic var openCost: Double = 0.0 //建仓成本
dynamic var openCharge:Double = 0.0 //建仓手续费
dynamic var closePrice:Double = 0.0 //平仓价格
dynamic var closeTime: uint = 0 //平仓时间
dynamic var closeIncome: Double = 0.0 //平仓收入
dynamic var closeCharge: Double = 0.0 //平仓手续费
dynamic var closeType: Int8 = 0 //平仓类型
dynamic var closeName:String? //平仓名称
}
| apache-2.0 | e9ec99ef17e6178cd5f566a545f965b0 | 36.779661 | 72 | 0.512786 | 4.001795 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmo/LocationModel.swift | 2 | 2376 | //
// LocationModel.swift
// iOsmo
//
// Created by Olga Grineva on 13/12/14.
// Copyright (c) 2014 Olga Grineva, (c) 2017 Alexey Sirotkin All rights reserved.
//
import Foundation
public struct LocationModel{
var lat: Double
var lon: Double
var speed: Double = -1.0
var alt: Int = 0
var course: Float = 0.0
var accuracy: Int = 0
var time: Date
let coordFormat = "%.6f"
let speedFormat = "S%.2f"
let courseFormat = "C%.0f"
let timeFormat = "T%.0f"
init(lat: Double, lon: Double){
self.lat = lat
self.lon = lon
self.time = Date()
}
init(coordString: String){
//G:1578|["17397|L59.852968:30.373739S0","47580|L37.330178:-122.032674S3"]
//G:9938|["21542|L46.654809:31.020692S3A48","21646|L46.484945:30.689059S7A78"]
let parts = coordString.components(separatedBy: "S")
self.speed = atof(parts[1])
let coordinatesMerged = parts[0][parts[0].index(parts[0].startIndex, offsetBy: 1)...]
let coordinates = coordinatesMerged.components(separatedBy: ":")
self.lat = atof(coordinates[0])
self.lon = atof(coordinates[1])
let tparts = coordString.components(separatedBy: "T")
if tparts.count>1 {
self.time = Date(timeIntervalSince1970: atof(tparts[1]))
} else {
self.time = Date()
}
}
var getCoordinateRequest: String{
var isSimulated = false
if UIDevice.current.model == "iPhone Simulator" {
isSimulated = true
}
var formatedTime = ""
let t:TimeInterval = time.timeIntervalSince1970
formatedTime = NSString(format:timeFormat as NSString, t) as String
let formatedSpeed = speed > 0 ? (NSString(format:speedFormat as NSString, speed)): ""
let formatedCourse = (speed > 5 && course > 0) ? (NSString(format:courseFormat as NSString, course)): ""
let toSend = "L\(NSString(format:coordFormat as NSString, lat)):\(NSString(format:coordFormat as NSString, lon))\(formatedSpeed)A\(isSimulated ? randRange(5, upper: 125) : alt)\(formatedCourse)H\(accuracy)\(formatedTime)"
return toSend
}
fileprivate func randRange (_ lower: UInt32 , upper: UInt32) -> Int {
return (Int)(lower + arc4random_uniform(upper - lower + 1))
}
}
| gpl-3.0 | cee6594fc6a20fd4cc3ebf101ce28aca | 32 | 229 | 0.61069 | 3.700935 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmo/ConnectionManager.swift | 2 | 49608 | //
// ConnectionManager.swift
// iOsmo
//
// Created by Olga Grineva on 13/12/14.
// Copyright (c) 2014 Olga Grineva, (c) 2019 Alexey Sirotkin All rights reserved.
//
// implementations of Singleton: https://github.com/hpique/SwiftSingleton
// implement http://stackoverflow.com/questions/9810585/how-to-get-reachability-notifications-in-ios-in-background-when-dropping-wi-fi-n
import Foundation
import CoreLocation
import AudioToolbox
import AVFoundation
let iOsmoAppKey = "EfMNuZdpaGGYoQmWXZ4b"
open class ConnectionManager: NSObject{
private let bgController = ConnectionHelper()
var monitoringGroupsHandler: ObserverSetEntry<[UserGroupCoordinate]>?
var onGroupListUpdated: ObserverSetEntry<[Group]>?
var onMessageListUpdated: ObserverSetEntry<(Int)>?
//var onGroupCreated: ObserverSetEntry<(Int, String)>?
// add name of group in return
let groupEntered = ObserverSet<(Int, String)>()
let groupCreated = ObserverSet<(Int, String)>()
let groupLeft = ObserverSet<(Int, String)>()
let groupActivated = ObserverSet<(Int, String)>()
let groupsUpdated = ObserverSet<(Int, Any)>()
let messagesUpdated = ObserverSet<(Int, Any)>()
let messageSent = ObserverSet<(Int, String)>()
let pushActivated = ObserverSet<Int>()
let groupDeactivated = ObserverSet<(Int, String)>()
let groupListDownloaded = ObserverSet<[Group]>()
let groupList = ObserverSet<[Group]>()
let connectionRun = ObserverSet<(Int, String)>()
let sessionRun = ObserverSet<(Int, String)>()
let groupsEnabled = ObserverSet<Int>()
let messageOfTheDayReceived = ObserverSet<(Int, String)>()
let historyReceived = ObserverSet<(Int, Any)>()
let connectionClose = ObserverSet<()>()
let connectionStart = ObserverSet<()>()
let dataSendStart = ObserverSet<()>()
let dataReceiveEnd = ObserverSet<()>()
let dataSendEnd = ObserverSet<()>()
let conHelper = ConnectionHelper()
let monitoringGroupsUpdated = ObserverSet<[UserGroupCoordinate]>()
fileprivate let log = LogQueue.sharedLogQueue
private var Authenticated = false
open var device_key: String = ""
open var permanent: Bool = false
open var sessionTrackerID: String = ""
open func getTrackerID()-> String?{return sessionTrackerID}
private var sessionUrlParsed: String = ""
open func getSessionUrl() -> String? {return "https://osmo.mobi/s/\(sessionUrlParsed)"}
var delayedRequests : [String] = [];
var transports: [Transport] = [Transport]()
var privacyList: [Private] = [Private]()
var connection = BaseTcpConnection()
var coordinates: [LocationModel]
var sendingCoordinates = false;
fileprivate let aSelector : Selector = #selector(ConnectionManager.reachabilityChanged(_:))
open var shouldReConnect = false
open var isGettingLocation = false
var serverToken: Token
var reachability: Reachability?
open var transportType: Int = 0;
open var trip_privacy : Int = -1;
var audioPlayer = AVAudioPlayer()
public var timer = Timer()
class var sharedConnectionManager : ConnectionManager{
struct Static {
static let instance: ConnectionManager = ConnectionManager()
}
return Static.instance
}
override init(){
let reachability: Reachability?
reachability = try? Reachability()
self.reachability = reachability
coordinates = [LocationModel]()
self.serverToken = Token(tokenString: "", address: "", port:0, key: "")
super.init()
NotificationCenter.default.addObserver(self, selector: aSelector, name: NSNotification.Name.reachabilityChanged, object: reachability)
do {
try reachability?.startNotifier()
}catch{
print("could not start reachability notifier")
}
//!! subscribtion for almost all types events
_ = connection.answerObservers.add(notifyAnswer)
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)), mode: AVAudioSession.Mode.default)
} catch {
log.enqueue("CM.Inint: Unable to set AVAudioSessionCategory \(error)")
}
}
func getServerInfo(key:String?) {
conHelper.onCompleted = {(dataURL, data) in
var res : NSDictionary = [:]
var tkn : Token;
LogQueue.sharedLogQueue.enqueue("CM.getServerInfo.onCompleted")
guard let data = data else {
tkn = Token(tokenString:"", address: "", port: 0, key: "")
tkn.error = "Server address not received"
self.completed(result: false, token: tkn)
return
}
if let output = String(data:data, encoding:.utf8) {
LogQueue.sharedLogQueue.enqueue("server: \(output)")
}
do {
let jsonDict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers);
res = (jsonDict as? NSDictionary)!
if let server = res[Keys.address.rawValue] as? String {
let server_arr = server.components(separatedBy: ":")
if server_arr.count > 1 {
if let tknPort = Int(server_arr[1]) {
self.serverToken = Token(tokenString:"", address: server_arr[0], port: tknPort, key: key! as String)
self.completed(result: true,token: self.serverToken)
return
}
}
tkn = Token(tokenString:"", address: "", port: -1, key: "")
tkn.error = "Server address not parsed"
self.completed(result: false, token: tkn)
} else {
tkn = Token(tokenString:"", address: "", port: -1, key: "")
tkn.error = "Server address not received"
self.completed(result: false, token: tkn)
}
} catch {
LogQueue.sharedLogQueue.enqueue("error serializing JSON from POST")
tkn = Token(tokenString:"", address: "", port: -1, key: "")
tkn.error = "error serializing JSON"
self.completed(result: false, token: tkn)
}
}
LogQueue.sharedLogQueue.enqueue("CM.getServerInfo")
let requestString = "app=\(iOsmoAppKey)"
conHelper.backgroundRequest(URL(string: URLs.servUrl)!, requestBody: requestString as NSString)
}
func Authenticate () {
let device = SettingsManager.getKey(SettingKeys.device)
if device == nil || device?.length == 0{
LogQueue.sharedLogQueue.enqueue("CM.Authenticate:getting key from server")
conHelper.onCompleted = {(dataURL, data) in
guard let data = data else { return }
var res : NSDictionary = [:]
do {
let jsonDict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers);
res = (jsonDict as? NSDictionary)!
if let newKey = res[Keys.device.rawValue] as? String {
LogQueue.sharedLogQueue.enqueue("CM.Authenticate: got key from server \(newKey)")
SettingsManager.setKey(newKey as NSString, forKey: SettingKeys.device)
self.Authenticated = true
self.getServerInfo(key: newKey)
} else {
}
} catch {
LogQueue.sharedLogQueue.enqueue("CM.Authenticate: error serializing key")
}
}
let vendorKey = UIDevice.current.identifierForVendor!.uuidString
let model = UIDevice.current.modelName
let version = UIDevice.current.systemVersion
let requestString = "app=\(iOsmoAppKey)&id=\(vendorKey)&platform=\(model) iOS \(version)"
conHelper.backgroundRequest(URL(string: URLs.authUrl)!, requestBody: requestString as NSString)
} else {
LogQueue.sharedLogQueue.enqueue("CM.Authenticate:using local key \(device!)")
self.Authenticated = true
self.getServerInfo(key: device! as String)
}
}
@objc open func reachabilityChanged(_ note: Notification) {
log.enqueue("CM.reachability changed")
let reachability = note.object as! Reachability
reachabilityStatus = reachability.connection
switch reachability.connection {
case .wifi:
//reachabilityStatus = .reachableViaWiFi
print("Reachable via WiFi")
if (!self.connected) {
log.enqueue("should be reconnected via WiFi")
shouldReConnect = true;
}
case .cellular:
//reachabilityStatus = .reachableViaWWAN
print("Reachable via Cellular")
if (!self.connected) {
log.enqueue("should be reconnected via Cellular")
shouldReConnect = true;
}
case .unavailable:
if (self.connected) {
self.connected = false
self.sendingCoordinates = false
log.enqueue("should be reconnected")
shouldReConnect = true;
connectionRun.notify((1, "")) //error but is not need to be popuped
}
}
if (shouldReConnect) {
self.connecting = false
log.enqueue("Reconnect action")
connect()
}
}
open var sessionUrl: String? { get { return self.getSessionUrl() } }
open var TrackerID: String? { get { return self.getTrackerID() } }
open var connected: Bool = false
open var sessionOpened: Bool = false
private var connecting: Bool = false
/*Информация о сервере получена*/
private func completed (result: Bool, token: Token?) {
self.connecting = false
if (result) {
if self.connection.addCallBackOnError == nil {
self.connection.addCallBackOnError = {
(isError : Bool) -> Void in
self.connecting = false
self.shouldReConnect = isError
self.connected = false
self.connectionRun.notify((1, ""))
if (self.shouldReConnect) {
//self.connect()
if (!self.timer.isValid) {
self.log.enqueue("CM.completed scheduling connect by timer")
self.timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(self.connectByTimer), userInfo: nil, repeats: true)
}
}
}
}
if self.connection.addCallBackOnSendStart == nil {
self.connection.addCallBackOnSendStart = {
() -> Void in
self.dataSendStart.notify(())
}
}
if self.connection.addCallBackOnReceiveEnd == nil {
self.connection.addCallBackOnReceiveEnd = {
() -> Void in
self.dataReceiveEnd.notify(())
if (!self.connected) { //Восстановления коннекта после обрыва
self.connected = true
}
}
}
if self.connection.addCallBackOnSendEnd == nil {
self.connection.addCallBackOnSendEnd = {
(message) -> Void in
let command = message.components(separatedBy: "|").first!
if (command == Tags.coordinate.rawValue || command == Tags.buffer.rawValue) {
self.sendingCoordinates = true
}
self.dataSendEnd.notify(()) //Передаем событие подписчикам
}
}
if self.connection.addCallBackOnCloseConnection == nil {
self.connection.addCallBackOnCloseConnection = {
() -> Void in
self.connecting = false
self.connected = false
self.sendingCoordinates = false
self.connectionClose.notify(())
}
}
if self.connection.addCallBackOnConnect == nil {
self.connection.addCallBackOnConnect = {
() -> Void in
self.connecting = false
if (self.timer.isValid) {
self.timer.invalidate()
}
let device = SettingsManager.getKey(SettingKeys.device)! as String
let request = "\(Tags.auth.rawValue)\(device)"
self.connection.send(request)
}
}
self.connection.connect(token!)
self.shouldReConnect = false //interesting why here? may after connction is successful??
} else {
if (token != nil) {
if (token?.error.isEmpty)! {
self.connectionRun.notify((1, ""))
self.shouldReConnect = false
} else {
self.log.enqueue("CM.completed Error:\(token?.error ?? "")")
if (token?.error == "Wrong device key") {
SettingsManager.setKey("", forKey: SettingKeys.device)
self.connectionRun.notify((1, ""))
self.shouldReConnect = true
} else {
if (token?.port ?? 0 >= 0 ) {
self.connectionRun.notify((1, "\(token?.error ?? "")"))
} else {
self.connectionRun.notify((1, ""))
}
self.shouldReConnect = false
}
}
} else {
self.log.enqueue("CM.completed Error: Invalid data")
self.connectionRun.notify((1, "Invalid data"))
self.shouldReConnect = false
}
}
}
open func connect(){
log.enqueue("CM: connect")
self.sendingCoordinates = false
if self.connecting {
log.enqueue("Conection already in process")
return;
}
if self.connected {
log.enqueue("Already connected !")
return;
}
self.connecting = true;
/*
if !isNetworkAvailable {
log.enqueue("Network is NOT available")
shouldReConnect = true
self.connecting = false;
return
}*/
self.connectionStart.notify(())
self.Authenticate()
}
open func closeConnection() {
if (self.connected && !self.sessionOpened) {
connection.closeConnection()
self.connected = false
self.Authenticated = false
self.sendingCoordinates = false
}
}
open func openSession(){
log.enqueue("CM.openSession")
if (self.connected && !self.sessionOpened) {
let json: NSDictionary = ["transportid": self.transportType, "private": self.trip_privacy]
do{
let data = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions(rawValue: 0))
if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
let request = "\(Tags.openSession.rawValue)|\(jsonString)"
send(request: request)
}
}catch {
print("error generating trip open info")
}
}
}
open func closeSession(){
log.enqueue("CM.closeSession")
self.trip_privacy = -1
if self.sessionOpened {
let request = "\(Tags.closeSession.rawValue)"
connection.send(request)
}
}
open func send(request: String) {
let command = request.components(separatedBy: "|").first!
if (self.connected || command == Tags.coordinate.rawValue || command == Tags.buffer.rawValue || self.connecting) {
connection.send(request)
} else {
if (UIApplication.shared.applicationState == .active ) {
log.enqueue("CM.send appActive or coorinate")
delayedRequests.append(request)
if (!self.timer.isValid) {
log.enqueue("CM.send scheduling connect by timer")
self.timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.connectByTimer), userInfo: nil, repeats: true)
}
} else {
log.enqueue("CM.send appInActive")
self.connecting = false;
let device = SettingsManager.getKey(SettingKeys.device)! as String
let escapedRequest = request.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
if let url = URL(string: (URLs.apiUrl + "k=" + device + "&m=" + escapedRequest! ) ) {
conHelper.onCompleted = {(dataURL, data) in
guard let data = data else { return }
LogQueue.sharedLogQueue.enqueue("CM.Send.onCompleted")
if let output = String(data:data, encoding:.utf8) {
LogQueue.sharedLogQueue.enqueue(output)
self.notifyAnswer(output: output)
}
}
conHelper.backgroundRequest(url, requestBody: "")
}
}
}
}
//Попытка посстановить соединение после обрыва, по срабатыванию таймера
@objc func connectByTimer() {
self.connecting = false
self.connect()
}
//probably should be refactored and moved to ReconnectManager
fileprivate func sendPing(){
self.send(request:"\(Tags.ping.rawValue)")
}
open func sendCoordinate(_ coordinate: LocationModel) {
let request = "\(Tags.remoteCommandResponse.rawValue)\(RemoteCommand.WHERE.rawValue)|\(coordinate.getCoordinateRequest)"
send(request: request)
}
open func sendCoordinates(_ coordinates: [LocationModel])
{
if self.sessionOpened {
self.coordinates += coordinates
/* Время первой локации в списке неотправлкнных старее чем 1.5 минуты и есть незаконченная опытка отправки ? */
if (-self.coordinates[0].time.timeIntervalSinceNow > 30 && self.sendingCoordinates) {
self.sendingCoordinates = false; /* Сбрасываем признак активной отправки координат*/
}
if (!self.sendingCoordinates) {
self.sendNextCoordinates()
}
}
}
open func sendRemoteCommandResponse(_ rc: String) {
let request = "\(Tags.remoteCommandResponse.rawValue)\(rc)|1"
send(request: request)
}
// Groups funcs
open func getGroups(){
if self.onGroupListUpdated == nil {
self.onGroupListUpdated = self.groupListDownloaded.add{
self.groupList.notify($0)
}
}
self.sendGetGroups()
}
open func getChatMessages(u: Int){
self.send(request: "\(Tags.groupChat.rawValue):\(u)")
}
open func createGroup(_ name: String, email: String, nick: String){
/*
if self.onGroupCreated == nil {
print("CM.creatGroup add onGroupCreated")
self.onGroupCreated = self.groupCreated.add{
print("CM.onGroupCreated notify")
self.groupCreated.notify($0)
}
}
*/
let jsonInfo: NSDictionary =
["name": name as NSString, "email": email as NSString, "nick": nick as NSString]
do{
let data = try JSONSerialization.data(withJSONObject: jsonInfo, options: JSONSerialization.WritingOptions(rawValue: 0))
if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
let request = "\(Tags.createGroup.rawValue):|\(jsonString)"
send(request: request)
}
}catch {
print("error generating new group info")
}
}
open func enterGroup(_ name: String, nick: String){
let request = "\(Tags.enterGroup.rawValue)\(name)|\(nick)"
send(request: request)
}
open func leaveGroup(_ u: String){
let request = "\(Tags.leaveGroup.rawValue)\(u)"
send(request: request)
}
//Активация-деактиация получени обновления координат из группы
open func activatePoolGroups(_ s: Int){
let request = "\(Tags.activatePoolGroups.rawValue):\(s)"
send(request: request)
}
open func groupsSwitch(_ s: Int){
let request = "\(Tags.groupSwitch.rawValue)"
send(request: request)
}
open func activateGroup(_ u: String){
let request = "\(Tags.activateGroup.rawValue)\(u)"
send(request: request)
}
open func deactivateGroup(_ u: String){
let request = "\(Tags.deactivateGroup.rawValue)\(u)"
send(request: request)
}
open func sendGetGroups(){
let request = "\(Tags.getGroups.rawValue)"
send(request: request)
}
open func sendTrackUser(_ user_id:String){
let request = "\(Tags.setTrackedkUser.rawValue):\(user_id)|1"
send(request: request)
}
open func sendUpdateGroupResponse(group: Int, event:Int){
let request = "\(Tags.updateGroupResponse.rawValue):\(group)|\(event)"
send(request: request)
}
open func sendChatMessage(group: Int, text: String){
let jsonInfo: NSDictionary = ["text": text]
do{
let data = try JSONSerialization.data(withJSONObject: jsonInfo, options: JSONSerialization.WritingOptions(rawValue: 0))
if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
let request = "\(Tags.groupChatSend.rawValue):\(group)|\(jsonString)"
send(request: request)
}
}catch {
print("error generating system info")
}
}
open func getMessageOfTheDay(){
let request = "\(Tags.messageDay.rawValue)"
send(request: request)
}
open func getHistory(){
let request = "\(Tags.history.rawValue)"
send(request: request)
}
open func sendPush(_ token: String){
let request = "\(Tags.push.rawValue)|\(token)"
if connected {
send(request: request)
}
}
open func sendSystemInfo(){
let model = UIDevice.current.modelName
let version = UIDevice.current.systemVersion
let appVersion : String! = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String ?? "unknown"
let jsonInfo: NSDictionary = ["devicename": model, "version": "iOS \(version)", "app":"\(appVersion!)"]
do{
let data = try JSONSerialization.data(withJSONObject: jsonInfo, options: JSONSerialization.WritingOptions(rawValue: 0))
if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
let request = "\(Tags.remoteCommandResponse.rawValue)\(RemoteCommand.TRACKER_SYSTEM_INFO.rawValue)|\(jsonString)"
send(request: request)
}
}catch {
print("error generating system info")
}
}
open func sendBatteryStatus(_ rc: String){
UIDevice.current.isBatteryMonitoringEnabled = true
let level = Int(UIDevice.current.batteryLevel * 100)
var state = 0;
if (UIDevice.current.batteryState == .charging) {
state = 1;
}
let jsonInfo: NSDictionary = ["percent": level, "plugged": state]
do{
let data = try JSONSerialization.data(withJSONObject: jsonInfo, options: JSONSerialization.WritingOptions(rawValue: 0))
if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
let request = "\(Tags.remoteCommandResponse.rawValue)\(RemoteCommand.TRACKER_BATTERY_INFO.rawValue)|\(jsonString)"
send(request: request)
}
}catch {
print("error generating battery info")
}
}
//MARK private methods
var isNetworkAvailable : Bool {
return reachabilityStatus != .unavailable
}
var reachabilityStatus: Reachability.Connection = .unavailable
//fileprivate func notifyAnswer(_ tag: AnswTags, name: String, answer: Int){
fileprivate func notifyAnswer(output: String){
var command = output.components(separatedBy: "|").first!
let index = command.count + 1
let addict = index < output.count ? String(output[output.index(output.startIndex, offsetBy: index)..<output.endIndex]) : ""
var param = ""
if command.contains(":"){
param = command.components(separatedBy: ":").last!
command = command.components(separatedBy: ":").first!
}
var answer : Int = 0;
var name: String;
if command == AnswTags.auth.rawValue {
//ex: INIT|{"id":"CVH2SWG21GW","group":1,"motd":1429351583,"protocol":2,"v":0.88} || INIT|{"id":1,"error":"Token is invalid"}
if let result = parseForErrorJson(output) {
answer = result.0
name = result.1
if result.0 == 0 {
//means response to try connecting
log.enqueue("connected with Auth")
self.connecting = false
self.connected = answer == 0;
let js = parseJson(output) as! Dictionary<String, AnyObject>;
if let json_array = js["transport"] as? Array<AnyObject> {
self.transports = [Transport]();
for t in json_array {
let tt = Transport.init(json: (t as! Dictionary<String, AnyObject>));
self.transports.append(tt);
}
}
if let json_array = js["private"] as? Array<AnyObject> {
self.privacyList = [Private]();
for t in json_array {
let p = Private.init(json: (t as! Dictionary<String, AnyObject>));
self.privacyList.append(p);
}
}
if let trackerID = parseTag(output, key: Keys.id) {
sessionTrackerID = trackerID
} else {
sessionTrackerID = "error parsing TrackerID"
}
if let user = parseTag(output, key: Keys.name) {
SettingsManager.setKey(user as NSString, forKey: SettingKeys.user)
}
if let uid = parseTag(output, key: Keys.uid) {
SettingsManager.setKey(uid as NSString, forKey: SettingKeys.uid)
}
if let spermanent = parseTag(output, key: Keys.permanent) {
if spermanent == "1" {
self.permanent = true;
}
}
if let motd = parseTag(output, key: Keys.motd) {
let cur_motd = SettingsManager.getKey(SettingKeys.motdtime) as String? ?? "0"
if (Int(motd)! > Int(cur_motd)!) {
SettingsManager.setKey(motd as NSString, forKey: SettingKeys.motdtime)
self.getMessageOfTheDay()
}
}
if (answer == 10 || answer == 100) {
DispatchQueue.main.async {
SettingsManager.clearKeys()
self.connection.closeConnection()
self.connect()
}
} else {
if (!self.connected) {
self.shouldReConnect = false
} else {
for request in self.delayedRequests {
self.send(request: request)
}
self.delayedRequests = []
}
if let trackerId = self.TrackerID {
SettingsManager.setKey(trackerId as NSString, forKey: SettingKeys.trackerId)
}
connectionRun.notify((answer, name))
}
} else {
connectionRun.notify((answer, name))
}
}
return
}
if command == AnswTags.enterGroup.rawValue {
if let result = parseForErrorJson(output){
groupEntered.notify((result.0, result.1))
} else {
log.enqueue("error: enter group asnwer cannot be parsed")
}
return
}
if command == AnswTags.leaveGroup.rawValue {
if let result = parseForErrorJson(output){
groupLeft.notify((result.0, result.1))
}else {
log.enqueue("error: leave group asnwer cannot be parsed")
}
return
}
if command == AnswTags.activateGroup.rawValue {
if let result = parseForErrorJson(output){
let value = (result.0==1 ? result.1 : (result.1=="" ? output.components(separatedBy: "|")[1] : result.1 ))
groupActivated.notify((result.0, value))
}else {
log.enqueue("error: activate group asnwer cannot be parsed")
}
return
}
if command == AnswTags.deactivateGroup.rawValue {
if let result = parseForErrorJson(output){
groupDeactivated.notify((result.0, result.1))
}else {
log.enqueue("error: deactivate group asnwer cannot be parsed")
}
return
}
if command == AnswTags.updateGroup.rawValue {
let parseRes = parseGroupUpdate(output)
if let grId = parseRes.0, let res = parseRes.1 {
groupsUpdated.notify((grId, res))
}else {
log.enqueue("error parsing GP")
}
return
}
if command == AnswTags.getGroups.rawValue {
if let result = parseGroupsJson(output) {
self.groupList.notify(result)
} else {
log.enqueue("error: groups list answer cannot be parsed")
}
return
}
if command == Tags.groupChat.rawValue {
let parseRes = parseGroupUpdate(output)
if let grId = parseRes.0, let res = parseRes.1 {
self.messagesUpdated.notify((grId, res))
}else {
log.enqueue("error: groups chat answer cannot be parsed")
}
return
}
if command == Tags.groupChatMessage.rawValue {
let parseRes = parseGroupUpdate(output)
if let grId = parseRes.0, let res = parseRes.1 {
self.messagesUpdated.notify((grId, res))
}else {
log.enqueue("error: groups chat message cannot be parsed")
}
return
}
if command == Tags.groupChatSend.rawValue {
if let result = parseForErrorJson(output){
messageSent.notify((result.0, result.1))
} else {
log.enqueue("error: message sent cannot be parsed")
}
return
}
if command == AnswTags.push.rawValue {
log.enqueue("PUSH activated")
if let result = parseForErrorJson(output){
pushActivated.notify(result.0)
}else {
log.enqueue("error: PUSH asnwer cannot be parsed")
}
return
}
if command == AnswTags.createGroup.rawValue {
if let result = parseForErrorJson(output){
let value = (result.0==1 ? result.1 : (result.1=="" ? output.components(separatedBy: "|")[1] : result.1 ))
groupCreated.notify((result.0, value))
return
} else {
log.enqueue("error: create group asnwer cannot be parsed")
}
return
}
if command == AnswTags.openedSession.rawValue {
log.enqueue("session opened answer") //ex: TO|{"session":145004,"url":"f1_o9_7s"}
if let result = parseForErrorJson(output){
answer = result.0
name = result.1
if result.0 == 0 {
sessionOpened = true
if let sessionUrl = parseTag(output, key: Keys.sessionUrl) {
sessionUrlParsed = sessionUrl
} else {
sessionUrlParsed = "error parsing url"
}
}
sessionRun.notify((answer, name))
return
} else {
log.enqueue("error: open session asnwer cannot be parsed")
}
return
}
if command == AnswTags.closeSession.rawValue {
log.enqueue("session closed answer")
if let result = parseForErrorJson(output){
answer = result.0
name = result.1
self.sessionOpened = answer != 0;
sessionRun.notify((answer == 0 ? 1 : 0, NSLocalizedString("session was closed", comment:"session was closed")))
}else {
log.enqueue("error: session closed asnwer cannot be parsed")
}
return
}
if command == AnswTags.kick.rawValue {
log.enqueue("connection kicked")
if parseForErrorJson(output) != nil{
self.connected = false
self.connection.closeConnection()
self.connect()
} else {
log.enqueue("kick asnwer cannot be parsed")
}
return
}
if command == AnswTags.pong.rawValue {
log.enqueue("server wants answer ;)")
sendPing()
return
}
if command == AnswTags.coordinate.rawValue {
let cnt = Int(addict)
if cnt ?? 0 > 0 {
self.onSentCoordinate(cnt:cnt!)
}
return
}
if command == AnswTags.buffer.rawValue {
let cnt = Int(addict)
if cnt ?? 0 > 0 {
self.onSentCoordinate(cnt:cnt!)
}
return
}
if command == AnswTags.grCoord.rawValue {
let parseRes = parseGroupUpdate(output)
if let grId = parseRes.0, let res = parseRes.1 {
if let userCoordinates = parseCoordinate(grId, coordinates: res) {
monitoringGroupsUpdated.notify(userCoordinates)
}
else {
log.enqueue("error: parsing coordinate array")
}
}
//D:47580|L37.33018:-122.032582S1.3A9H5C
//G:1578|["17397|L59.852968:30.373739S0","47580|L37.330178:-122.032674S3"]
return
}
if command == AnswTags.messageDay.rawValue {
if (command != "" && addict != "") {
SettingsManager.setKey(addict as NSString, forKey: SettingKeys.motd)
messageOfTheDayReceived.notify((1, addict))
}
else {
log.enqueue("error: wrong parsing MD")
}
return
}
if command == Tags.history.rawValue {
if (command != "" && addict != "") {
if let json = parseJson(output) {
historyReceived.notify((1, json))
}
}
else {
log.enqueue("error: wrong parsing HISTORY")
}
return
}
if command == AnswTags.remoteCommand.rawValue {
let sendingManger = SendingManager.sharedSendingManager
if (param == RemoteCommand.TRACKER_BATTERY_INFO.rawValue){
sendBatteryStatus(param)
return
}
if (param == RemoteCommand.TRACKER_SYSTEM_INFO.rawValue){
sendSystemInfo()
return
}
if (param == RemoteCommand.TRACKER_VIBRATE.rawValue){
//for _ in 1...3 {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
//sleep(1)
//}
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.ALARM_ON.rawValue){
if let fileURL = Bundle.main.path(forResource: "signal", ofType: "mp3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
audioPlayer.numberOfLoops = 3
audioPlayer.prepareToPlay()
audioPlayer.play()
sendRemoteCommandResponse(param)
} catch {
}
}
return
}
if (param == RemoteCommand.ALARM_OFF.rawValue){
if audioPlayer.isPlaying {
audioPlayer.stop()
sendRemoteCommandResponse(param)
}
return
}
if (param == RemoteCommand.TRACKER_SESSION_STOP.rawValue){
sendingManger.stopSendingCoordinates()
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.TRACKER_EXIT.rawValue){
sendingManger.stopSendingCoordinates()
sendRemoteCommandResponse(param)
connection.closeConnection()
return
}
if (param == RemoteCommand.TRACKER_SESSION_START.rawValue){
self.isGettingLocation = false
sendingManger.startSendingCoordinates(false)
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.TRACKER_SESSION_PAUSE.rawValue){
sendingManger.pauseSendingCoordinates(true)
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.TRACKER_SESSION_CONTINUE.rawValue){
sendingManger.startSendingCoordinates(false)
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.TRACKER_GCM_ID.rawValue) {
//Отправляем токен ранее полученный от FCM
if let token = Messaging.messaging().fcmToken {
sendPush(token)
}
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.REFRESH_GROUPS.rawValue){
sendGetGroups()
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.CHANGE_MOTD_TEXT.rawValue){
messageOfTheDayReceived.notify((1, addict))
sendRemoteCommandResponse(param)
return
}
if (param == RemoteCommand.WHERE.rawValue || param == RemoteCommand.WHERE_GPS_ONLY.rawValue || param == RemoteCommand.WHERE_NETWORK_ONLY.rawValue) {
sendRemoteCommandResponse(param)
if self.sessionOpened == false {
if (param == RemoteCommand.WHERE.rawValue) {
LocationTracker.sharedLocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
} else if (param == RemoteCommand.WHERE_GPS_ONLY.rawValue){
LocationTracker.sharedLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
} else if (param == RemoteCommand.WHERE_NETWORK_ONLY.rawValue){
LocationTracker.sharedLocationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}
self.isGettingLocation = true
sendingManger.startSendingCoordinates(true)
}
return
}
}
}
//MARK - parsing server response functions
func onSentCoordinate(cnt: Int){
log.enqueue("Removing \(cnt) coordinates from buffer")
for _ in 1...cnt {
if self.coordinates.count > 0 {
self.coordinates.remove(at: 0)
}
}
self.sendingCoordinates = false
self.sendNextCoordinates()
}
fileprivate func sendNextCoordinates(){
/*
if self.shouldCloseSession {
self.coordinates.removeAll(keepingCapacity: false)
closeSession()
}*/
//TODO: refactoring send best coordinates
let cnt = self.coordinates.count;
if self.sessionOpened && cnt > 0 {
var req = ""
var sep = ""
var idx = 0;
if cnt > 1 {
sep = "\""
}
for theCoordinate in self.coordinates {
if req != "" {
req = "\(req),"
}
req = "\(req)\(sep)\(theCoordinate.getCoordinateRequest)\(sep)"
idx = idx + 1
//Ограничиваем количество отправляемых точек в одном пакете
if idx > 500 {
break;
}
}
if cnt > 1 {
req = "\(Tags.buffer.rawValue)|[\(req)]"
} else {
req = "\(Tags.coordinate.rawValue)|\(req)"
}
send(request:req)
if (idx % 10 == 0 && !self.connected) { //Накопилось 10 координат а соединение разорвано?
self.connect() //Пытаемся восстановить соединение
}
}
}
fileprivate func parseCoordinate(_ group: Int, coordinates: Any) -> [UserGroupCoordinate]? {
if let users = coordinates as? Array<String> {
var res : [UserGroupCoordinate] = [UserGroupCoordinate]()
for u in users {
let uc = u.components(separatedBy: "|")
let user_id = Int(uc[0])
if ((user_id ?? 0) != 0) { //id
let location = LocationModel(coordString: uc[1])
let ugc: UserGroupCoordinate = UserGroupCoordinate(group: group, user: user_id!, location: location)
res.append(ugc)
}
}
return res
}
return nil
}
fileprivate func parseGroupUpdate(_ responce: String) -> (Int?, Any?){
let cmd = responce.components(separatedBy: "|")[0]
let groupId = Int(cmd.components(separatedBy: ":")[1])
return (groupId, parseJson(responce))
}
fileprivate func parseForErrorJson(_ responce: String) -> (Int, String)? {
if let dic = parseJson(responce) as? Dictionary<String, Any>{
if dic.index(forKey: "error") == nil {
return (0, "")
} else {
if let err = dic["error"] as? Int {
if let err_msg = dic["error_description"] as? String{
return (err, err_msg)
}else {
return (err, "\(err)")
}
}
return (1, "error message is not parsed")
}
} else {
if Int(responce.components(separatedBy: "|").last!)! > 0 {
return (0, "")
}
}
return nil
}
fileprivate func parseJson(_ responce: String) -> Any? {
// server can accumulate some messages, so should define it
//let responceFirst = responce.componentsSeparatedByString("\n")[0] <-- has no sense because splitting in other place
// should parse only first | sign, because of responce structure
// "TRACKER_SESSION_OPEN|{\"warn\":1,\"session\":\"40839\",\"url\":\"lGv|f2\"}\n"
let index = responce.components(separatedBy: "|")[0].count + 1
let json = responce[responce.index(responce.startIndex, offsetBy: index)..<responce.endIndex]
if let data: Data = json.data(using: String.Encoding.utf8) {
do {
let jsonObject: Any! = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
return jsonObject;
} catch {
return nil;
}
}
return nil
}
fileprivate func parseGroupsJson(_ responce: String) -> [Group]? {
//let responceFirst = responce.componentsSeparatedByString("\n")[0] <-- has no sense because splitting in other place
// should parse only first | sign, because of responce structure
// "TRACKER_SESSION_OPEN|{\"warn\":1,\"session\":\"40839\",\"url\":\"lGv|f2\"}\n"
let index = responce.components(separatedBy: "|")[0].count + 1
let json = responce[responce.index(responce.startIndex, offsetBy: index)..<responce.endIndex]
do {
if let data: Data = json.data(using: String.Encoding.utf8), let jsonObject: Any? = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) {
var groups = [Group]()
if let jsonGroups = jsonObject as? Array<Any> {
for jsonG in jsonGroups{
let group = Group.init(json: jsonG as! Dictionary<String, AnyObject>)
groups.append(group)
}
}
return groups
}
}catch {}
return nil
}
fileprivate func parseTag(_ responce: String, key: Keys) -> String? {
if let responceValues: NSDictionary = parseJson(responce) as? Dictionary<String, AnyObject> as NSDictionary? {
if let tag = responceValues.object(forKey: key.rawValue) as? String {
return tag
} else if let itag = responceValues.object(forKey: key.rawValue) as? Int {
return "\(itag)"
}
}
return nil
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
return input.rawValue
}
| gpl-3.0 | 99e41811bea82b980586b5540a3c17d6 | 37.805687 | 203 | 0.519174 | 5.33594 | false | false | false | false |
yulingtianxia/Spiral | Spiral/ContactVisitor.swift | 1 | 2014 | //
// ContactVistor.swift
// Spiral
//
// Created by 杨萧玉 on 14-7-14.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import Foundation
import SpriteKit
class ContactVisitor:NSObject{
let body:SKPhysicsBody!
let contact:SKPhysicsContact!
class func contactVisitorWithBody(_ body:SKPhysicsBody,forContact contact:SKPhysicsContact)->ContactVisitor?{
//第一次dispatch,通过node类别返回对应的实例
if 0 != body.categoryBitMask&playerCategory {
return PlayerContactVisitor(body: body, forContact: contact)
}
if 0 != body.categoryBitMask&killerCategory {
return KillerContactVisitor(body: body, forContact: contact)
}
if 0 != body.categoryBitMask&scoreCategory {
return ScoreContactVisitor(body: body, forContact: contact)
}
if 0 != body.categoryBitMask&shieldCategory {
return ShieldContactVisitor(body: body, forContact: contact)
}
if 0 != body.categoryBitMask&reaperCategory {
return ReaperContactVisitor(body: body, forContact: contact)
}
if 0 != body.categoryBitMask&eyeCategory {
return EyeContactVisitor(body: body, forContact: contact)
}
return nil
}
init(body:SKPhysicsBody, forContact contact:SKPhysicsContact){
self.body = body
self.contact = contact
super.init()
}
func visitBody(_ body:SKPhysicsBody){
//第二次dispatch,通过构造方法名来执行对应方法
// 生成方法名,比如"visitPlayer"
let contactSelectorString = "visit" + body.node!.name! + ":"
let selector = Selector(contactSelectorString)
if self.responds(to: selector){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: {
Thread.detachNewThreadSelector(selector, toTarget:self, with: body)
})
}
}
}
| apache-2.0 | 3afe807bd8060f25272de3d2765c7ee1 | 31.508475 | 113 | 0.631387 | 4.666667 | false | false | false | false |
Antidote-for-Tox/Antidote-for-Mac | Antidote/LabelView.swift | 1 | 695 | //
// LabelView.swift
// Antidote
//
// Created by Yoba on 18/12/2016.
// Copyright © 2016 Dmytro Vorobiov. All rights reserved.
//
import Cocoa
/**
Kind of normal non-editable label without a border
*/
class LabelView: NSTextField {
required init?(coder: NSCoder) {
super.init(coder: coder)
}
init(fontSize: CGFloat = 12.0) {
super.init(frame: NSZeroRect)
self.isBezeled = false
self.drawsBackground = false
self.isEditable = false
self.isSelectable = false
self.lineBreakMode = .byTruncatingTail
self.font = NSFont.systemFont(ofSize: fontSize)
self.maximumNumberOfLines = 0
}
}
| gpl-3.0 | 82716ce1fb8008682849df9ddaa53943 | 21.387097 | 58 | 0.62536 | 4.130952 | false | false | false | false |
maximedegreve/TinyFaces | Sources/App/Models/Avatar.swift | 1 | 1973 | import Fluent
import Vapor
final class Avatar: Model, Content {
static let schema = "avatars"
@ID(custom: .id)
var id: Int?
@Parent(key: "source_id")
var source: Source
@Field(key: "url")
var url: String
@Enum(key: "gender")
var gender: Gender
@Field(key: "quality")
var quality: Int
@Field(key: "approved")
var approved: Bool
@Timestamp(key: "created_at", on: .create)
var createdAt: Date?
@Timestamp(key: "updated_at", on: .update)
var updatedAt: Date?
@Timestamp(key: "deleted_at", on: .delete)
var deletedAt: Date?
init() { }
init(url: String, sourceId: Int, gender: Gender, quality: Int, approved: Bool) {
self.$source.id = sourceId
self.url = url
self.gender = gender
self.quality = quality
self.approved = approved
}
}
extension Avatar {
static func createIfNotExist(req: Request, sourceId: Int, externalUrl: String, gender: Gender, quality: Int, approved: Bool) -> EventLoopFuture<Avatar> {
return Avatar.query(on: req.db).filter(\.$source.$id == sourceId).first().flatMap { optionalAvatar -> EventLoopFuture<Avatar> in
if let avatar = optionalAvatar {
return req.eventLoop.future(avatar)
}
let isProduction = req.application.environment == .production
let folder = isProduction ? "facebook" : "facebook-dev"
return Cloudinary().upload(file: externalUrl, eager: CloudinaryPresets.avatarMaxSize, publicId: nil, folder: folder, transformation: nil, format: "jpg", client: req.client).flatMap { cloudinaryResponse in
let newAvatar = Avatar(url: cloudinaryResponse.secureUrl, sourceId: sourceId, gender: gender, quality: quality, approved: approved)
return newAvatar.save(on: req.db).transform(to: newAvatar)
}
}
}
}
| mit | ce0810262434f39edf86302b88474acf | 27.185714 | 216 | 0.609731 | 4.153684 | false | false | false | false |
hal11/iOSPopExtensions | iOSPopExtensions/PopSpringViewSizeProtocol.swift | 1 | 1415 | //
// PopSpringViewSizeProtocol.swift
// iOSPopExtensions
//
// Created by 矢野 春樹 on 2016/05/12.
// Copyright © 2016年 矢野 春樹. All rights reserved.
//
import pop
public protocol PopSpringViewSize{
var selfView: UIView{ get }
var springViewSizeFrom: CGSize?{ get }
var springViewSizeTo: CGSize{ get }
var springViewSizeBounciness: CGFloat{ get }
var springViewSizeSpeed: CGFloat{ get }
/**
デリゲートは下記の3つ
func pop_animationDidStart(animation:POPAnimation)
func pop_animationDidStop(animation:POPAnimation)s.requires_arc = true
func pop_animationDidReachToValue(animation:POPAnimation)
*/
var springViewSizeDelegate: AnyObject?{ get }
}
extension PopSpringViewSize{
public func playSpringViewSize(){
let SpringAnimation = POPSpringAnimation()
SpringAnimation.property = POPAnimatableProperty.propertyWithName(kPOPViewSize) as! POPAnimatableProperty
if let from = springViewSizeFrom{
SpringAnimation.fromValue = NSValue(CGSize: from)
}
SpringAnimation.toValue = NSValue(CGSize: springViewSizeTo)
SpringAnimation.springBounciness = springViewSizeBounciness
SpringAnimation.springSpeed = springViewSizeSpeed
SpringAnimation.delegate = springViewSizeDelegate
selfView.pop_addAnimation(SpringAnimation, forKey: "size")
}
} | mit | a5d12c4d572efe631148794604bb7acf | 33.275 | 113 | 0.724818 | 4.724138 | false | false | false | false |
JGiola/swift | stdlib/public/BackDeployConcurrency/CheckedContinuation.swift | 1 | 11721 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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 Swift
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_continuation_logFailedCheck")
internal func logFailedCheck(_ message: UnsafeRawPointer)
/// Implementation class that holds the `UnsafeContinuation` instance for
/// a `CheckedContinuation`.
@available(SwiftStdlib 5.1, *)
internal final class CheckedContinuationCanary: @unchecked Sendable {
// The instance state is stored in tail-allocated raw memory, so that
// we can atomically check the continuation state.
private init() { fatalError("must use create") }
private static func _create(continuation: UnsafeRawPointer, function: String)
-> Self {
let instance = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
(UnsafeRawPointer?, String).self)
instance._continuationPtr.initialize(to: continuation)
instance._functionPtr.initialize(to: function)
return instance
}
private var _continuationPtr: UnsafeMutablePointer<UnsafeRawPointer?> {
return UnsafeMutablePointer<UnsafeRawPointer?>(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
}
private var _functionPtr: UnsafeMutablePointer<String> {
let tailPtr = UnsafeMutableRawPointer(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
let functionPtr = tailPtr
+ MemoryLayout<(UnsafeRawPointer?, String)>.offset(of: \(UnsafeRawPointer?, String).1)!
return functionPtr.assumingMemoryBound(to: String.self)
}
internal static func create<T, E>(continuation: UnsafeContinuation<T, E>,
function: String) -> Self {
return _create(
continuation: unsafeBitCast(continuation, to: UnsafeRawPointer.self),
function: function)
}
internal var function: String {
return _functionPtr.pointee
}
// Take the continuation away from the container, or return nil if it's
// already been taken.
internal func takeContinuation<T, E>() -> UnsafeContinuation<T, E>? {
// Atomically exchange the current continuation value with a null pointer.
let rawContinuationPtr = unsafeBitCast(_continuationPtr,
to: Builtin.RawPointer.self)
let rawOld = Builtin.atomicrmw_xchg_seqcst_Word(rawContinuationPtr,
0._builtinWordValue)
return unsafeBitCast(rawOld, to: UnsafeContinuation<T, E>?.self)
}
deinit {
_functionPtr.deinitialize(count: 1)
// Log if the continuation was never consumed before the instance was
// destructed.
if _continuationPtr.pointee != nil {
logFailedCheck("SWIFT TASK CONTINUATION MISUSE: \(function) leaked its continuation!\n")
}
}
}
/// A mechanism to interface
/// between synchronous and asynchronous code,
/// logging correctness violations.
///
/// A *continuation* is an opaque representation of program state.
/// To create a continuation in asynchronous code,
/// call the `withUnsafeContinuation(function:_:)` or
/// `withUnsafeThrowingContinuation(function:_:)` function.
/// To resume the asynchronous task,
/// call the `resume(returning:)`,
/// `resume(throwing:)`,
/// `resume(with:)`,
/// or `resume()` method.
///
/// - Important: You must call a resume method exactly once
/// on every execution path throughout the program.
///
/// Resuming from a continuation more than once is undefined behavior.
/// Never resuming leaves the task in a suspended state indefinitely,
/// and leaks any associated resources.
/// `CheckedContinuation` logs a message
/// if either of these invariants is violated.
///
/// `CheckedContinuation` performs runtime checks
/// for missing or multiple resume operations.
/// `UnsafeContinuation` avoids enforcing these invariants at runtime
/// because it aims to be a low-overhead mechanism
/// for interfacing Swift tasks with
/// event loops, delegate methods, callbacks,
/// and other non-`async` scheduling mechanisms.
/// However, during development, the ability to verify that the
/// invariants are being upheld in testing is important.
/// Because both types have the same interface,
/// you can replace one with the other in most circumstances,
/// without making other changes.
@available(SwiftStdlib 5.1, *)
public struct CheckedContinuation<T, E: Error> {
private let canary: CheckedContinuationCanary
/// Creates a checked continuation from an unsafe continuation.
///
/// Instead of calling this initializer,
/// most code calls the `withCheckedContinuation(function:_:)` or
/// `withCheckedThrowingContinuation(function:_:)` function instead.
/// You only need to initialize
/// your own `CheckedContinuation<T, E>` if you already have an
/// `UnsafeContinuation` you want to impose checking on.
///
/// - Parameters:
/// - continuation: An instance of `UnsafeContinuation`
/// that hasn't yet been resumed.
/// After passing the unsafe continuation to this initializer,
/// don't use it outside of this object.
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
public init(continuation: UnsafeContinuation<T, E>, function: String = #function) {
canary = CheckedContinuationCanary.create(
continuation: continuation,
function: function)
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// - Parameter value: The value to return from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
public func resume(returning value: __owned T) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(returning: value)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, returning \(value)!\n")
}
}
/// Resume the task awaiting the continuation by having it throw an error
/// from its suspension point.
///
/// - Parameter error: The error to throw from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
public func resume(throwing error: __owned E) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(throwing: error)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, throwing \(error)!\n")
}
}
}
@available(SwiftStdlib 5.1, *)
extension CheckedContinuation: Sendable where T: Sendable { }
@available(SwiftStdlib 5.1, *)
extension CheckedContinuation {
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume<Er: Error>(with result: Result<T, Er>) where E == Error {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume(with result: Result<T, E>) {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume() where T == Void {
self.resume(returning: ())
}
}
/// Suspends the current task,
/// then calls the given closure with a checked continuation for the current task.
///
/// - Parameters:
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
/// - body: A closure that takes a `CheckedContinuation` parameter.
/// You must resume the continuation exactly once.
@available(SwiftStdlib 5.1, *)
public func withCheckedContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Never>) -> Void
) async -> T {
return await withUnsafeContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
/// Suspends the current task,
/// then calls the given closure with a checked throwing continuation for the current task.
///
/// - Parameters:
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
/// - body: A closure that takes an `UnsafeContinuation` parameter.
/// You must resume the continuation exactly once.
///
/// If `resume(throwing:)` is called on the continuation,
/// this function throws that error.
@available(SwiftStdlib 5.1, *)
public func withCheckedThrowingContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Error>) -> Void
) async throws -> T {
return try await withUnsafeThrowingContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
| apache-2.0 | 6f0697f298ef03888dd8404d8ec18f90 | 38.332215 | 141 | 0.701049 | 4.760764 | false | false | false | false |
ahoppen/swift | test/IRGen/partial_apply_crash.swift | 22 | 807 | // RUN: %target-swift-frontend -emit-ir -O %s | %FileCheck %s
// This is a compile-only test. It checks that the compiler does not crash for
// a partial_apply with "unusual" conformances: rdar://problem/59456064
public struct Inner<Element> { }
extension Inner: Equatable where Element: Equatable {
public static func == (lhs: Inner<Element>, rhs: Inner<Element>) -> Bool {
return false
}
}
public struct Outer<Value> { }
extension Outer: Equatable where Value: Equatable {
public static func == (lhs: Outer<Value>, rhs: Outer<Value>) -> Bool {
return false
}
}
@inline(never)
func foo<Element>(_ x: Element, _ equal: (Element, Element) -> Bool) {
_ = equal(x, x)
}
// CHECK: define {{.*}}testit
public func testit<Element: Equatable>(_ x: Outer<Inner<Element>>) {
foo(x, ==)
}
| apache-2.0 | 30562c64a089239258f4bdbfd8f1b6a6 | 25.032258 | 78 | 0.667906 | 3.419492 | false | true | false | false |
Codility-BMSTU/Codility | Codility/Codility/OBQuest.swift | 1 | 1473 | //
// OBQuest.swift
// OpenBank
//
// Created by Aleksander Evtuhov on 17/09/2017.
// Copyright © 2017 Aleksander Evtuhov. All rights reserved.
//
import Foundation
class OBQuest{
var name : String
var howToAchive : String
var reward : Int
var stage : Int
var progressMax : Int
var progressCurent : Int
init(nameP : String, howToAchiveP : String, rewardP : Int, stageP : Int, progressMaxP : Int, progressCurentP : Int){
self.name = nameP
self.howToAchive = howToAchiveP
self.reward = rewardP
self.stage = stageP
self.progressMax = progressMaxP
self.progressCurent = progressCurentP
}
static func getTestData()->[OBQuest]{
var quests = [OBQuest]()
quests.append(OBQuest(nameP: "Вклады", howToAchiveP: "Открой вклад", rewardP: 200, stageP: 0, progressMaxP: 1, progressCurentP: 0))
quests.append(OBQuest(nameP: "Кредиты", howToAchiveP: "Возьми 2 кредита", rewardP: 500, stageP: 1, progressMaxP: 2, progressCurentP: 1))
quests.append(OBQuest(nameP: "Покупки", howToAchiveP: "Потрать 30 000 на покупки", rewardP: 100, stageP: 2, progressMaxP: 30000, progressCurentP: 10000))
quests.append(OBQuest(nameP: "Опрос", howToAchiveP: "Прими участие в опросе", rewardP: 13, stageP: 3, progressMaxP: 1, progressCurentP: 1))
return quests
}
}
| apache-2.0 | c2c9529d6512d48bb8ea462ec8729f52 | 37.555556 | 161 | 0.664265 | 3.920904 | false | false | false | false |
turekj/ReactiveTODO | ReactiveTODOTests/Classes/Controls/SegmentedControls/Impl/PriorityPickerSpec.swift | 1 | 2646 | @testable import ReactiveTODOFramework
import Nimble
import Quick
class PriorityPickerSpec: QuickSpec {
override func spec() {
describe("PriorityPicker") {
let validator = PriorityValidatorMock()
let priorities = [Priority.Urgent, Priority.Low]
let sut = PriorityPicker(validator: Validator(validator),
priorities: priorities)
it("Should map priorities to raw values") {
expect(sut.numberOfSegments).to(equal(2))
expect(sut.titleForSegmentAtIndex(0)).to(equal("Urgent"))
expect(sut.titleForSegmentAtIndex(1)).to(equal("Low"))
}
it("Should bind invalid priorities to nil") {
sut.priority.value = .Low
validator.isValid = false
self.firePriorityPickerChange(sut, selectedIndex: 0)
expect(sut.priority.value).toEventually(beNil())
}
it("Should bind valid priorities to values") {
sut.priority.value = nil
validator.isValid = true
self.firePriorityPickerChange(sut, selectedIndex: 0)
expect(sut.priority.value).toEventually(equal(Priority.Urgent))
}
it("Should have valid value border color for valid priority") {
sut.priority.value = Priority.High
expect(sut.layer.borderColor)
.toEventually(equal(UIColor.validValueColor().CGColor))
}
it("Should have invalid value border color for invalid priority") {
sut.priority.value = nil
expect(sut.layer.borderColor)
.toEventually(equal(UIColor.invalidValueColor().CGColor))
}
it("Should have valid value tint color for valid priority") {
sut.priority.value = Priority.High
expect(sut.tintColor)
.toEventually(equal(UIColor.validValueColor()))
}
it("Should have invalid value tint color for invalid priority") {
sut.priority.value = nil
expect(sut.tintColor)
.toEventually(equal(UIColor.invalidValueColor()))
}
}
}
private func firePriorityPickerChange(priorityPicker: PriorityPicker,
selectedIndex: Int) {
dispatch_async(dispatch_get_main_queue()) {
priorityPicker.selectedSegmentIndex = selectedIndex
priorityPicker.sendActionsForControlEvents(.ValueChanged)
}
}
}
| mit | 7b60dc09f6fa8a6b35c4216f457422a7 | 34.28 | 79 | 0.572184 | 5.45567 | false | false | false | false |
ontouchstart/swift3-playground | playground2book/MyPlayground.playground/Contents.swift | 2 | 687 | /*:
# ImageContext
*/
import UIKit
import PlaygroundSupport
let size = CGSize(width: 400, height: 400)
UIGraphicsBeginImageContext(size)
let frame = CGRect(x: 0, y: 0, width: 400, height: 100)
let text = "Hello world 🌎"
let textFontAttributes = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 48.0),
NSForegroundColorAttributeName: UIColor.white,
NSBackgroundColorAttributeName: UIColor.blue
]
text.draw(in: frame, withAttributes: textFontAttributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let iV = UIImageView(image: image)
let vC = UIViewController()
vC.view.addSubview(iV)
PlaygroundPage.current.liveView = vC | mit | b31de0cbe5bd50ec14785716e307b081 | 22.62069 | 61 | 0.77193 | 4.275 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Foundation/URL.swift | 1 | 62119 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// Keys used in the result of `URLResourceValues.thumbnailDictionary`.
@available(OSX 10.10, iOS 8.0, *)
public struct URLThumbnailSizeKey : RawRepresentable, Hashable {
public typealias RawValue = String
public init(rawValue: RawValue) { self.rawValue = rawValue }
private(set) public var rawValue: RawValue
/// Key for a 1024 x 1024 thumbnail image.
static public let none: URLThumbnailSizeKey = URLThumbnailSizeKey(rawValue: URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue)
public var hashValue: Int {
return rawValue.hashValue
}
}
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(OSX 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(OSX)
/// True if the resource is scriptable. Only applies to applications.
@available(OSX 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(OSX)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(OSX)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(OSX 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if let isNull = _values[.quarantinePropertiesKey] as? NSNull {
return nil
} else {
return _values[.quarantinePropertiesKey] as? [String : Any]
}
}
set {
if let v = newValue {
_set(.quarantinePropertiesKey, newValue: newValue as NSObject?)
} else {
// Set to NSNull, a special case for deleting quarantine properties
_set(.quarantinePropertiesKey, newValue: NSNull())
}
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if !os(OSX)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String, relativeTo url: URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(OSX 10.11, iOS 9.0, *)
public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(OSX 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(OSX 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(OSX 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(OSX 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(OSX 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(OSX 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(OSX 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(OSX 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| apache-2.0 | 9644e5d9fb4d35f769f76d1d25d1fa47 | 50.636741 | 765 | 0.681563 | 4.991081 | false | false | false | false |
srn214/Floral | Floral/Pods/SwiftyAttributes/SwiftyAttributes/Sources/common/Attribute+Sequence.swift | 2 | 1130 | //
// AttributeConversions.swift
// SwiftyAttributes
//
// Created by Eddie Kaiger on 11/23/16.
// Copyright © 2016 Eddie Kaiger. All rights reserved.
//
/**
An extension on dictionaries that allows us to convert a Foundation-based dictionary of attributes to an array of `Attribute`s.
*/
extension Dictionary where Key == NSAttributedString.Key {
/// Returns an array of `Attribute`s converted from the dictionary of attributes. Use this whenever you want to convert [NSAttributeStringKey: Any] to [Attribute].
public var swiftyAttributes: [Attribute] {
return map(Attribute.init)
}
}
extension Sequence where Iterator.Element == Attribute {
/// Returns the attribute dictionary required by Foundation's API for attributed strings. Use this whenever you need to convert [Attribute] to [String: Any].
public var foundationAttributes: [NSAttributedString.Key: Any] {
return reduce([NSAttributedString.Key: Any]()) { dictionary, attribute in
var dict = dictionary
dict[attribute.keyName] = attribute.foundationValue
return dict
}
}
}
| mit | 8390e9cf94de236220e383ae56a3b465 | 33.212121 | 167 | 0.707706 | 4.627049 | false | false | false | false |
IsaScience/ListerAProductivityAppObj-CandSwift | original-src/ListerAProductivityAppObj-CandSwift/Swift/Lister/ListDocumentsViewController.swift | 1 | 13777 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListDocumentsViewController` displays a list of available documents for users to open.
*/
import UIKit
import ListerKit
class ListDocumentsViewController: UITableViewController, ListControllerDelegate, UIDocumentMenuDelegate, UIDocumentPickerDelegate {
// MARK: Types
struct MainStoryboard {
struct ViewControllerIdentifiers {
static let listViewController = "listViewController"
static let listViewNavigationController = "listViewNavigationController"
}
struct TableViewCellIdentifiers {
static let listDocumentCell = "listDocumentCell"
}
struct SegueIdentifiers {
static let newListDocument = "newListDocument"
static let showListDocument = "showListDocument"
static let showListDocumentFromUserActivity = "showListDocumentFromUserActivity"
}
}
// MARK: Properties
var listController: ListController! {
didSet {
listController.delegate = self
}
}
private var pendingUserActivity: NSUserActivity? = nil
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: List.Color.Gray.colorValue
]
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleContentSizeCategoryDidChangeNotification:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: List.Color.Gray.colorValue
]
let grayListColor = List.Color.Gray.colorValue
navigationController?.navigationBar.tintColor = grayListColor
navigationController?.toolbar?.tintColor = grayListColor
tableView.tintColor = grayListColor
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let activity = pendingUserActivity {
restoreUserActivityState(activity)
}
pendingUserActivity = nil
}
// MARK: Lifetime
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
// MARK: UIResponder
override func restoreUserActivityState(activity: NSUserActivity) {
/**
If there is a list currently displayed; pop to the root view controller (this controller) and
continue the activity from there. Otherwise, continue the activity directly.
*/
if navigationController?.topViewController is UINavigationController {
navigationController?.popToRootViewControllerAnimated(false)
pendingUserActivity = activity
return
}
if let activityURL = activity.userInfo?[NSUserActivityDocumentURLKey] as? NSURL {
let activityListInfo = ListInfo(URL: activityURL)
let rawListInfoColor = activity.userInfo![AppConfiguration.UserActivity.listColorUserInfoKey]! as Int
activityListInfo.color = List.Color.fromRaw(rawListInfoColor)
performSegueWithIdentifier(MainStoryboard.SegueIdentifiers.showListDocumentFromUserActivity, sender: activityListInfo)
}
}
// MARK: IBActions
/**
Note that the document picker requires that code signing, entitlements, and provisioning for
the project have been configured before you run Lister. If you run the app without configuring
entitlements correctly, an exception when this method is invoked (i.e. when the "+" button is
clicked).
*/
@IBAction func pickDocument(barButtonItem: UIBarButtonItem) {
let documentMenu = UIDocumentMenuViewController(documentTypes: [AppConfiguration.listerUTI], inMode: .Open)
documentMenu.delegate = self
let newDocumentTitle = NSLocalizedString("New List", comment: "")
documentMenu.addOptionWithTitle(newDocumentTitle, image: nil, order: .First) {
// Show the NewListDocumentController.
self.performSegueWithIdentifier(MainStoryboard.SegueIdentifiers.newListDocument, sender: self)
}
documentMenu.modalPresentationStyle = .Popover
documentMenu.popoverPresentationController?.barButtonItem = barButtonItem
presentViewController(documentMenu, animated: true, completion: nil)
}
// MARK: UIDocumentMenuDelegate
func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
presentViewController(documentPicker, animated: true, completion: nil)
}
func documentMenuWasCancelled(documentMenu: UIDocumentMenuViewController) {
/**
The user cancelled interacting with the document menu. In your own app, you may want to
handle this with other logic.
*/
}
// MARK: UIPickerViewDelegate
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
// The user selected the document and it should be picked up by the `ListController`.
}
func documentPickerWasCancelled(controller: UIDocumentPickerViewController) {
/**
The user cancelled interacting with the document picker. In your own app, you may want to
handle this with other logic.
*/
}
// MARK: ListControllerDelegate
func listControllerWillChangeContent(listController: ListController) {
dispatch_async(dispatch_get_main_queue(), tableView.beginUpdates)
}
func listController(listController: ListController, didInsertListInfo listInfo: ListInfo, atIndex index: Int) {
dispatch_async(dispatch_get_main_queue()) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
func listController(listController: ListController, didRemoveListInfo listInfo: ListInfo, atIndex index: Int) {
dispatch_async(dispatch_get_main_queue()) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
func listController(listController: ListController, didUpdateListInfo listInfo: ListInfo, atIndex index: Int) {
dispatch_async(dispatch_get_main_queue()) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as ListCell
cell.label.text = listInfo.name
listInfo.fetchInfoWithCompletionHandler {
dispatch_async(dispatch_get_main_queue()) {
// Make sure that the list info is still visible once the color has been fetched.
let indexPathsForVisibleRows = self.tableView.indexPathsForVisibleRows() as [NSIndexPath]
if find(indexPathsForVisibleRows, indexPath) != nil {
cell.listColorView.backgroundColor = listInfo.color!.colorValue
}
}
}
}
}
func listControllerDidChangeContent(listController: ListController) {
dispatch_async(dispatch_get_main_queue(), tableView.endUpdates)
}
func listController(listController: ListController, didFailCreatingListInfo listInfo: ListInfo, withError error: NSError) {
dispatch_async(dispatch_get_main_queue()) {
let title = NSLocalizedString("Failed to Create List", comment: "")
let message = error.localizedDescription
let okActionTitle = NSLocalizedString("OK", comment: "")
let errorOutController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: okActionTitle, style: .Cancel, handler: nil)
errorOutController.addAction(action)
self.presentViewController(errorOutController, animated: true, completion: nil)
}
}
func listController(listController: ListController, didFailRemovingListInfo listInfo: ListInfo, withError error: NSError) {
dispatch_async(dispatch_get_main_queue()) {
let title = NSLocalizedString("Failed to Delete List", comment: "")
let message = error.localizedFailureReason
let okActionTitle = NSLocalizedString("OK", comment: "")
let errorOutController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: okActionTitle, style: .Cancel, handler: nil)
errorOutController.addAction(action)
self.presentViewController(errorOutController, animated: true, completion: nil)
}
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// If the controller is nil, return no rows. Otherwise return the number of total rows.
return listController?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listDocumentCell, forIndexPath: indexPath) as ListCell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
switch cell {
case let listCell as ListCell:
let listInfo = listController[indexPath.row]
listCell.label.text = listInfo.name
listCell.label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
listCell.listColorView.backgroundColor = UIColor.clearColor()
// Once the list info has been loaded, update the associated cell's properties.
listInfo.fetchInfoWithCompletionHandler {
dispatch_async(dispatch_get_main_queue()) {
// Make sure that the list info is still visible once the color has been fetched.
let indexPathsForVisibleRows = self.tableView.indexPathsForVisibleRows() as [NSIndexPath]
if find(indexPathsForVisibleRows, indexPath) != nil {
listCell.listColorView.backgroundColor = listInfo.color!.colorValue
}
}
}
default:
fatalError("Attempting to configure an unknown or unsupported cell type in ListDocumentViewController.")
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: UIStoryboardSegue Handling
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == MainStoryboard.SegueIdentifiers.newListDocument {
let newListController = segue.destinationViewController as NewListDocumentController
newListController.listController = self.listController
}
else if segue.identifier == MainStoryboard.SegueIdentifiers.showListDocument || segue.identifier == MainStoryboard.SegueIdentifiers.showListDocumentFromUserActivity {
let listNavigationController = segue.destinationViewController as UINavigationController
let listViewController = listNavigationController.topViewController as ListViewController
listViewController.listController = listController
listViewController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
listViewController.navigationItem.leftItemsSupplementBackButton = true
if segue.identifier == MainStoryboard.SegueIdentifiers.showListDocument {
let indexPath = tableView.indexPathForSelectedRow()!
listViewController.configureWithListInfo(listController[indexPath.row])
}
else if segue.identifier == MainStoryboard.SegueIdentifiers.showListDocumentFromUserActivity {
let userActivityListInfo = sender as ListInfo
listViewController.configureWithListInfo(userActivityListInfo)
}
}
}
// MARK: Notifications
func handleContentSizeCategoryDidChangeNotification(_: NSNotification) {
tableView.setNeedsLayout()
}
}
| apache-2.0 | 295512269f8d4afdec0e6d4a79787c9b | 42.454259 | 186 | 0.669256 | 6.503777 | false | false | false | false |
EyreFree/UICountingLabel | EFCountingLabel/EFCount.swift | 1 | 5376 | //
// EFCount.swift
// EFCountingLabel
//
// Created by Kirow on 2019/05/14.
//
// Copyright (c) 2017 EyreFree <[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
import QuartzCore
public protocol EFTiming {
func update(_ time: CGFloat) -> CGFloat
}
public protocol EFCount {
func countFrom(_ startValue: CGFloat, to endValue: CGFloat, withDuration duration: TimeInterval)
func countFromCurrentValueTo(_ endValue: CGFloat, withDuration duration: TimeInterval)
func stopCountAtCurrentValue()
}
extension EFCount {
public func countFromZeroTo(_ endValue: CGFloat, withDuration duration: TimeInterval) {
countFrom(0, to: endValue, withDuration: duration)
}
public func countFrom(_ startValue: CGFloat, to endValue: CGFloat) {
countFrom(startValue, to: endValue, withDuration: 2)
}
public func countFromCurrentValueTo(_ endValue: CGFloat) {
countFromCurrentValueTo(endValue, withDuration: 2)
}
public func countFromZeroTo(_ endValue: CGFloat) {
countFromZeroTo(endValue, withDuration: 2)
}
}
public class EFCounter {
public var timingFunction: EFTiming = EFTimingFunction.linear
public var updateBlock: ((CGFloat) -> Void)?
public var completionBlock: (() -> Void)?
public private(set) var fromValue: CGFloat = 0
public private(set) var toValue: CGFloat = 1
private var currentDuration: TimeInterval = 0
public private(set) var totalDuration: TimeInterval = 1
private var lastUpdate: TimeInterval = 0
private var timer: CADisplayLink?
public var isCounting: Bool {
return timer != nil
}
public var progress: CGFloat {
guard totalDuration != 0 else { return 1 }
return CGFloat(currentDuration / totalDuration)
}
public var currentValue: CGFloat {
if currentDuration == 0 {
return 0
} else if currentDuration >= totalDuration {
return toValue
}
return fromValue + timingFunction.update(progress) * (toValue - fromValue)
}
public init() {
}
// CADisplayLink callback
@objc public func updateValue(_ timer: Timer) {
let now = CACurrentMediaTime()
currentDuration += now - lastUpdate
lastUpdate = now
if currentDuration >= totalDuration {
invalidate()
currentDuration = totalDuration
}
updateBlock?(currentValue)
if currentDuration == totalDuration {
runCompletionBlock()
}
}
private func runCompletionBlock() {
if let tryCompletionBlock = completionBlock {
completionBlock = nil
tryCompletionBlock()
}
}
//set init values
public func reset() {
invalidate()
fromValue = 0
toValue = 1
currentDuration = 0
lastUpdate = 0
totalDuration = 1
}
public func invalidate() {
timer?.invalidate()
timer = nil
}
}
extension EFCounter: EFCount {
public func countFromCurrentValueTo(_ endValue: CGFloat, withDuration duration: TimeInterval) {
countFrom(currentValue, to: endValue, withDuration: duration)
}
public func countFrom(_ startValue: CGFloat, to endValue: CGFloat, withDuration duration: TimeInterval) {
fromValue = startValue
toValue = endValue
// remove any (possible) old timers
invalidate()
if duration == 0.0 {
// No animation
updateBlock?(endValue)
runCompletionBlock()
return
}
currentDuration = 0
totalDuration = duration
lastUpdate = CACurrentMediaTime()
let timer = CADisplayLink(target: self, selector: #selector(updateValue(_:)))
if #available(iOS 10.0, *) {
timer.preferredFramesPerSecond = 30
} else {
timer.frameInterval = 2
}
timer.add(to: .main, forMode: .default)
timer.add(to: .main, forMode: .tracking)
self.timer = timer
}
public func stopCountAtCurrentValue() {
invalidate()
updateBlock?(currentValue)
}
}
| gpl-2.0 | 9360b8ff205e46d03d853954e6563445 | 30.075145 | 109 | 0.641741 | 5.071698 | false | false | false | false |
quver/SlidableImage | Sources/SlidableImage/SlidableImageFactory.swift | 1 | 2237 | //
// SlidableImageFactory.swift
// SlidableImage
//
// Created by Pawel Bednorz on 04.03.2017.
// Copyright © 2017 Quver. All rights reserved.
//
import UIKit
extension SlidableImage {
struct Factory {
static func makeSliderCircle(sliderImage: UIImage? = nil) -> UIView {
let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let circle = UIView(frame: frame)
guard let sliderImage = sliderImage else {
return ArrowsView(frame: frame)
}
circle.layer.cornerRadius = circle.bounds.width / 2
let imageView = UIImageView(image: sliderImage)
imageView.contentMode = .scaleAspectFill
circle.addSubview(imageView)
imageView.center = circle.center
return circle
}
static func makeContainer(image: UIImage, frame: CGRect) -> UIImageView {
let imageView = UIImageView(frame: frame)
imageView.image = image
imageView.contentMode = .scaleAspectFill
return imageView
}
static func makeMaskRect(for maskLocation: CGFloat, bounds: CGRect, slideDirection: Direction) -> CGRect {
switch slideDirection {
case .left:
return CGRect(x: maskLocation,
y: bounds.minY,
width: bounds.width,
height: bounds.height)
case .right:
return CGRect(x: bounds.minX,
y: bounds.minY,
width: maskLocation,
height: bounds.height)
case .top:
return CGRect(x: bounds.minX,
y: maskLocation,
width: bounds.width,
height: bounds.height)
case .bottom:
return CGRect(x: bounds.minX,
y: bounds.minY,
width: bounds.width,
height: maskLocation)
}
}
}
}
| mit | f8784b3dd58ec76235a2e86affc7f957 | 33.9375 | 114 | 0.480769 | 5.507389 | false | false | false | false |
Tomikes/eidolon | Kiosk/App/Models/SystemTime.swift | 7 | 1252 | import Foundation
import ISO8601DateFormatter
import ReactiveCocoa
class SystemTime {
var systemTimeInterval: NSTimeInterval? = nil
init () {}
func syncSignal() -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.SystemTime
return XAppRequest(endpoint).filterSuccessfulStatusCodes().mapJSON()
.doNext { [weak self] (response) -> Void in
if let dictionary = response as? NSDictionary {
let formatter = ISO8601DateFormatter()
let artsyDate = formatter.dateFromString(dictionary["iso8601"] as! String?)
self?.systemTimeInterval = NSDate().timeIntervalSinceDate(artsyDate)
}
}.doError { (error) -> Void in
logger.log("Error contacting Artsy servers: \(error.localizedDescription)")
}
}
func inSync() -> Bool {
return systemTimeInterval != nil
}
func date() -> NSDate {
let now = NSDate()
if let systemTimeInterval = systemTimeInterval {
return now.dateByAddingTimeInterval(-systemTimeInterval)
} else {
return now
}
}
func reset() {
systemTimeInterval = nil
}
}
| mit | d5a2de35136db80ae235b7da18918600 | 28.116279 | 95 | 0.585463 | 5.769585 | false | false | false | false |
kevin00223/iOS-demo | rac_demo/Pods/ReactiveCocoa/ReactiveCocoa/NSObject+KeyValueObserving.swift | 1 | 14708 | import Foundation
import ReactiveSwift
import enum Result.NoError
extension Reactive where Base: NSObject {
/// Create a producer which sends the current value and all the subsequent
/// changes of the property specified by the key path.
///
/// The producer completes when the object deinitializes.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func producer(forKeyPath keyPath: String) -> SignalProducer<Any?, NoError> {
return SignalProducer { observer, lifetime in
let disposable = KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.initial, .new],
action: observer.send
)
lifetime.observeEnded(disposable.dispose)
if let lifetimeDisposable = self.lifetime.observeEnded(observer.sendCompleted) {
lifetime.observeEnded(lifetimeDisposable.dispose)
}
}
}
/// Create a signal all changes of the property specified by the key path.
///
/// The signal completes when the object deinitializes.
///
/// - note:
/// Does not send the initial value. See `producer(forKeyPath:)`.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func signal(forKeyPath keyPath: String) -> Signal<Any?, NoError> {
return Signal { observer, signalLifetime in
signalLifetime += KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.new],
action: observer.send
)
signalLifetime += lifetime.observeEnded(observer.sendCompleted)
}
}
}
extension Property where Value: OptionalProtocol {
/// Create a property that observes the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to observe.
public convenience init(object: NSObject, keyPath: String) {
// `Property(_:)` caches the latest value of the `DynamicProperty`, so it is
// saved to be used even after `object` deinitializes.
self.init(UnsafeKVOProperty(object: object, optionalAttributeKeyPath: keyPath))
}
}
extension Property {
/// Create a property that observes the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to observe.
public convenience init(object: NSObject, keyPath: String) {
// `Property(_:)` caches the latest value of the `DynamicProperty`, so it is
// saved to be used even after `object` deinitializes.
self.init(UnsafeKVOProperty(object: object, nonOptionalAttributeKeyPath: keyPath))
}
}
// `Property(unsafeProducer:)` is private to ReactiveSwift. So the fact that
// `Property(_:)` uses only the producer is explioted here to achieve the same effect.
private final class UnsafeKVOProperty<Value>: PropertyProtocol {
var value: Value { fatalError() }
var signal: Signal<Value, NoError> { fatalError() }
let producer: SignalProducer<Value, NoError>
init(producer: SignalProducer<Value, NoError>) {
self.producer = producer
}
convenience init(object: NSObject, nonOptionalAttributeKeyPath keyPath: String) {
self.init(producer: object.reactive.producer(forKeyPath: keyPath).map { $0 as! Value })
}
}
private extension UnsafeKVOProperty where Value: OptionalProtocol {
convenience init(object: NSObject, optionalAttributeKeyPath keyPath: String) {
self.init(producer: object.reactive.producer(forKeyPath: keyPath).map {
return Value(reconstructing: $0.optional as? Value.Wrapped)
})
}
}
extension BindingTarget {
/// Create a binding target that sets the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to set.
public init(object: NSObject, keyPath: String) {
self.init(lifetime: object.reactive.lifetime) { [weak object] value in
object?.setValue(value, forKey: keyPath)
}
}
}
internal final class KeyValueObserver: NSObject {
typealias Action = (_ object: AnyObject?) -> Void
private static let context = UnsafeMutableRawPointer.allocate(bytes: 1, alignedTo: 0)
unowned(unsafe) let unsafeObject: NSObject
let key: String
let action: Action
fileprivate init(observing object: NSObject, key: String, options: NSKeyValueObservingOptions, action: @escaping Action) {
self.unsafeObject = object
self.key = key
self.action = action
super.init()
object.addObserver(
self,
forKeyPath: key,
options: options,
context: KeyValueObserver.context
)
}
func detach() {
unsafeObject.removeObserver(self, forKeyPath: key, context: KeyValueObserver.context)
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
if context == KeyValueObserver.context {
action(object as! NSObject)
}
}
}
extension KeyValueObserver {
/// Establish an observation to the property specified by the key path
/// of `object`.
///
/// - warning: The observation would not be automatically removed when
/// `object` deinitializes. You must manually dispose of the
/// returned disposable before `object` completes its
/// deinitialization.
///
/// - parameters:
/// - object: The object to be observed.
/// - keyPath: The key path of the property to be observed.
/// - options: The desired configuration of the observation.
/// - action: The action to be invoked upon arrival of changes.
///
/// - returns: A disposable that would tear down the observation upon
/// disposal.
static func observe(
_ object: NSObject,
keyPath: String,
options: NSKeyValueObservingOptions,
action: @escaping (_ value: AnyObject?) -> Void
) -> AnyDisposable {
// Compute the key path head and tail.
let components = keyPath.components(separatedBy: ".")
precondition(!components.isEmpty, "Received an empty key path.")
let isNested = components.count > 1
let keyPathHead = components[0]
let keyPathTail = components[1 ..< components.endIndex].joined(separator: ".")
// The serial disposable for the head key.
//
// The inner disposable would be disposed of, and replaced with a new one
// when the value of the head key changes.
let headSerialDisposable = SerialDisposable()
// If the property of the head key isn't actually an object (or is a Class
// object), there is no point in observing the deallocation.
//
// If this property is not a weak reference to an object, we don't need to
// watch for it spontaneously being set to nil.
//
// Attempting to observe non-weak properties using dynamic getters will
// result in broken behavior, so don't even try.
let (shouldObserveDeinit, isWeak) = keyPathHead.withCString { cString -> (Bool, Bool) in
if let propertyPointer = class_getProperty(type(of: object), cString) {
let attributes = PropertyAttributes(property: propertyPointer)
return (attributes.isObject && attributes.objectClass != NSClassFromString("Protocol") && !attributes.isBlock, attributes.isWeak)
}
return (false, false)
}
// Establish the observation.
//
// The initial value is also handled by the closure below, if `Initial` has
// been specified in the observation options.
let observer: KeyValueObserver
if isNested {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options.union(.initial)) { object in
guard let value = object?.value(forKey: keyPathHead) as! NSObject? else {
headSerialDisposable.inner = nil
action(nil)
return
}
let headDisposable = CompositeDisposable()
headSerialDisposable.inner = headDisposable
if shouldObserveDeinit {
let disposable = value.reactive.lifetime.observeEnded {
if isWeak {
action(nil)
}
// Detach the key path tail observers eagarly.
headSerialDisposable.inner = nil
}
headDisposable += disposable
}
// Recursively add observers along the key path tail.
let disposable = KeyValueObserver.observe(
value,
keyPath: keyPathTail,
options: options.subtracting(.initial),
action: action
)
headDisposable += disposable
// Send the latest value of the key path tail.
action(value.value(forKeyPath: keyPathTail) as AnyObject?)
}
} else {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options) { object in
guard let value = object?.value(forKey: keyPathHead) as AnyObject? else {
action(nil)
return
}
// For a direct key path, the deinitialization needs to be
// observed only if the key path is a weak property.
if shouldObserveDeinit && isWeak {
let disposable = Lifetime.of(value).observeEnded {
action(nil)
}
headSerialDisposable.inner = disposable
}
// Send the latest value of the key.
action(value)
}
}
return AnyDisposable {
observer.detach()
headSerialDisposable.dispose()
}
}
}
/// A descriptor of the attributes and type information of a property in
/// Objective-C.
internal struct PropertyAttributes {
struct Code {
static let start = Int8(UInt8(ascii: "T"))
static let quote = Int8(UInt8(ascii: "\""))
static let nul = Int8(UInt8(ascii: "\0"))
static let comma = Int8(UInt8(ascii: ","))
struct ContainingType {
static let object = Int8(UInt8(ascii: "@"))
static let block = Int8(UInt8(ascii: "?"))
}
struct Attribute {
static let readonly = Int8(UInt8(ascii: "R"))
static let copy = Int8(UInt8(ascii: "C"))
static let retain = Int8(UInt8(ascii: "&"))
static let nonatomic = Int8(UInt8(ascii: "N"))
static let getter = Int8(UInt8(ascii: "G"))
static let setter = Int8(UInt8(ascii: "S"))
static let dynamic = Int8(UInt8(ascii: "D"))
static let ivar = Int8(UInt8(ascii: "V"))
static let weak = Int8(UInt8(ascii: "W"))
static let collectable = Int8(UInt8(ascii: "P"))
static let oldTypeEncoding = Int8(UInt8(ascii: "t"))
}
}
/// The class of the property.
let objectClass: AnyClass?
/// Indicate whether the property is a weak reference.
let isWeak: Bool
/// Indicate whether the property is an object.
let isObject: Bool
/// Indicate whether the property is a block.
let isBlock: Bool
init(property: objc_property_t) {
guard let attrString = property_getAttributes(property) else {
preconditionFailure("Could not get attribute string from property.")
}
precondition(attrString[0] == Code.start, "Expected attribute string to start with 'T'.")
let typeString = attrString + 1
let _next = NSGetSizeAndAlignment(typeString, nil, nil)
guard _next != typeString else {
let string = String(validatingUTF8: attrString)
preconditionFailure("Could not read past type in attribute string: \(String(describing: string)).")
}
var next = UnsafeMutablePointer<Int8>(mutating: _next)
let typeLength = typeString.distance(to: next)
precondition(typeLength > 0, "Invalid type in attribute string.")
var objectClass: AnyClass? = nil
// if this is an object type, and immediately followed by a quoted string...
if typeString[0] == Code.ContainingType.object && typeString[1] == Code.quote {
// we should be able to extract a class name
let className = typeString + 2;
// fast forward the `next` pointer.
guard let endQuote = strchr(className, Int32(Code.quote)) else {
preconditionFailure("Could not read class name in attribute string.")
}
next = endQuote
if className != UnsafePointer(next) {
let length = className.distance(to: next)
let name = UnsafeMutablePointer<Int8>.allocate(capacity: length + 1)
name.initialize(from: UnsafeMutablePointer<Int8>(mutating: className), count: length)
(name + length).initialize(to: Code.nul)
// attempt to look up the class in the runtime
objectClass = objc_getClass(name) as! AnyClass?
name.deinitialize(count: length + 1)
name.deallocate(capacity: length + 1)
}
}
if next.pointee != Code.nul {
// skip past any junk before the first flag
next = strchr(next, Int32(Code.comma))
}
let emptyString = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
emptyString.initialize(to: Code.nul)
defer {
emptyString.deinitialize()
emptyString.deallocate(capacity: 1)
}
var isWeak = false
while next.pointee == Code.comma {
let flag = next[1]
next += 2
switch flag {
case Code.nul:
break;
case Code.Attribute.readonly:
break;
case Code.Attribute.copy:
break;
case Code.Attribute.retain:
break;
case Code.Attribute.nonatomic:
break;
case Code.Attribute.getter:
fallthrough
case Code.Attribute.setter:
next = strchr(next, Int32(Code.comma)) ?? emptyString
case Code.Attribute.dynamic:
break
case Code.Attribute.ivar:
// assume that the rest of the string (if present) is the ivar name
if next.pointee != Code.nul {
next = emptyString
}
case Code.Attribute.weak:
isWeak = true
case Code.Attribute.collectable:
break
case Code.Attribute.oldTypeEncoding:
let string = String(validatingUTF8: attrString)
assertionFailure("Old-style type encoding is unsupported in attribute string \"\(String(describing: string))\"")
// skip over this type encoding
while next.pointee != Code.comma && next.pointee != Code.nul {
next += 1
}
default:
let pointer = UnsafeMutablePointer<Int8>.allocate(capacity: 2)
pointer.initialize(to: flag)
(pointer + 1).initialize(to: Code.nul)
let flag = String(validatingUTF8: pointer)
let string = String(validatingUTF8: attrString)
preconditionFailure("ERROR: Unrecognized attribute string flag '\(String(describing: flag))' in attribute string \"\(String(describing: string))\".")
}
}
if next.pointee != Code.nul {
let unparsedData = String(validatingUTF8: next)
let string = String(validatingUTF8: attrString)
assertionFailure("Warning: Unparsed data \"\(String(describing: unparsedData))\" in attribute string \"\(String(describing: string))\".")
}
self.objectClass = objectClass
self.isWeak = isWeak
self.isObject = typeString[0] == Code.ContainingType.object
self.isBlock = isObject && typeString[1] == Code.ContainingType.block
}
}
| mit | 1ca00ffe96b0278a8cb0b42207e80918 | 30.973913 | 153 | 0.698735 | 3.86341 | false | false | false | false |
JiongXing/PhotoBrowser | Example/Example/RawImageViewController.swift | 1 | 6008 | //
// RawImageViewController.swift
// Example
//
// Created by JiongXing on 2019/11/29.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
import JXPhotoBrowser
import SDWebImage
class RawImageViewController: BaseCollectionViewController {
override class func name() -> String { "显示查看原图" }
override class func remark() -> String { "举例如何实现查看原图" }
override func makeDataSource() -> [ResourceModel] {
let models = makeNetworkDataSource()
models[3].thirdLevelUrl = "https://github.com/JiongXing/PhotoBrowser/raw/master/Assets/rawImage.jpg"
return models
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.jx.dequeueReusableCell(BaseCollectionViewCell.self, for: indexPath)
if let firstLevel = self.dataSource[indexPath.item].firstLevelUrl {
let url = URL(string: firstLevel)
cell.imageView.sd_setImage(with: url, completed: nil)
}
return cell
}
override func openPhotoBrowser(with collectionView: UICollectionView, indexPath: IndexPath) {
let browser = JXPhotoBrowser()
browser.numberOfItems = {
self.dataSource.count
}
// 使用自定义的Cell
browser.cellClassAtIndex = { _ in
RawImageCell.self
}
browser.reloadCellAtIndex = { context in
let browserCell = context.cell as? RawImageCell
let collectionPath = IndexPath(item: context.index, section: indexPath.section)
let collectionCell = collectionView.cellForItem(at: collectionPath) as? BaseCollectionViewCell
let placeholder = collectionCell?.imageView.image
let urlString = self.dataSource[context.index].secondLevelUrl
let rawURLString = self.dataSource[context.index].thirdLevelUrl
browserCell?.reloadData(placeholder: placeholder, urlString: urlString, rawURLString: rawURLString)
}
browser.pageIndex = indexPath.item
browser.show()
}
}
/// 加上进度环的Cell
class RawImageCell: JXPhotoBrowserImageCell {
/// 进度环
let progressView = JXPhotoBrowserProgressView()
/// 查看原图按钮
var rawButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.white, for: .highlighted)
button.backgroundColor = UIColor.black.withAlphaComponent(0.08)
button.setTitle("查看原图", for: .normal)
button.setTitle("查看原图", for: .highlighted)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.layer.borderColor = UIColor.white.cgColor
button.layer.borderWidth = 1 / UIScreen.main.scale
button.layer.cornerRadius = 4
button.layer.masksToBounds = true
return button
}()
override func setup() {
super.setup()
addSubview(progressView)
rawButton.addTarget(self, action: #selector(onRawImageButton), for: .touchUpInside)
rawButton.isHidden = true
addSubview(rawButton)
}
override func layoutSubviews() {
super.layoutSubviews()
progressView.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
rawButton.sizeToFit()
rawButton.bounds.size.width += 14
rawButton.center = CGPoint(x: bounds.width / 2,
y: bounds.height - 35 - rawButton.bounds.height)
}
func reloadData(placeholder: UIImage?, urlString: String?, rawURLString: String?) {
self.rawURLString = rawURLString
progressView.progress = 0
rawButton.isHidden = true
let url = urlString.flatMap { URL(string: $0) }
imageView.sd_setImage(with: url, placeholderImage: placeholder, options: []) { [weak self] (_, error, _, _) in
if error == nil {
self?.setNeedsLayout()
}
// 原图如果有缓存就加载
self?.loadRawImageIfCached(placeholder: self?.imageView.image, rawURLString: rawURLString)
}
}
/// 尝试加载缓存的原图,completion回调传参:true-已加载缓存,false-没有缓存
private func loadRawImageIfCached(placeholder: UIImage?, rawURLString: String?) {
guard let rawString = rawURLString else {
return
}
SDImageCache.shared.containsImage(forKey: rawString, cacheType: .all) { [weak self] cacheType in
if cacheType == .none {
self?.rawButton.isHidden = false
return
}
self?.imageView.sd_setImage(with: URL(string: rawString), placeholderImage: placeholder, options: []) { (_, error, _, _) in
if error == nil {
self?.setNeedsLayout()
}
self?.rawButton.isHidden = (error == nil)
}
}
}
/// 保存原图url
private var rawURLString: String?
/// 响应查看原图按钮
@objc func onRawImageButton(_ button: UIButton) {
self.rawButton.isHidden = true
guard let url = rawURLString.flatMap({ URL(string: $0) }) else {
progressView.isHidden = true
return
}
imageView.sd_setImage(with: url, placeholderImage: imageView.image, options: [], progress: { [weak self] (received, total, _) in
if total > 0 {
self?.progressView.progress = CGFloat(received) / CGFloat(total)
}
}) { [weak self] (_, error, _, _) in
if error == nil {
self?.progressView.progress = 1.0
self?.setNeedsLayout()
} else {
self?.progressView.progress = 0
self?.rawButton.isHidden = false
}
}
}
}
| mit | b5f14c3996da7ede5d76de2da58a5087 | 36.811688 | 136 | 0.611197 | 4.79654 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Services/Service.MotionSensor.swift | 1 | 1378 | import Foundation
extension Service {
open class MotionSensor: Service {
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
motionDetected = getOrCreateAppend(
type: .motionDetected,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.motionDetected() })
name = get(type: .name, characteristics: unwrapped)
statusActive = get(type: .statusActive, characteristics: unwrapped)
statusFault = get(type: .statusFault, characteristics: unwrapped)
statusLowBattery = get(type: .statusLowBattery, characteristics: unwrapped)
statusTampered = get(type: .statusTampered, characteristics: unwrapped)
super.init(type: .motionSensor, characteristics: unwrapped)
}
// MARK: - Required Characteristics
public let motionDetected: GenericCharacteristic<Bool>
// MARK: - Optional Characteristics
public let name: GenericCharacteristic<String>?
public let statusActive: GenericCharacteristic<Bool>?
public let statusFault: GenericCharacteristic<UInt8>?
public let statusLowBattery: GenericCharacteristic<Enums.StatusLowBattery>?
public let statusTampered: GenericCharacteristic<UInt8>?
}
}
| mit | a11870a5905cd3af52ddee5942e26462 | 46.517241 | 87 | 0.67344 | 5.601626 | false | false | false | false |
PauloMigAlmeida/Signals | SwiftSignalKit/Signal_Reduce.swift | 1 | 1074 | import Foundation
public func reduceLeft<T, E>(value: T, f: (T, T) -> T)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal<T, E> { subscriber in
var currentValue = value
return signal.start(next: { next in
currentValue = f(currentValue, next)
}, error: { error in
subscriber.putError(error)
}, completed: {
subscriber.putNext(currentValue)
subscriber.putCompletion()
})
}
}
public func reduceLeft<T, E>(value: T, f: (T, T, T -> Void) -> T)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal<T, E> { subscriber in
var currentValue = value
let emit: T -> Void = { next in
subscriber.putNext(next)
}
return signal.start(next: { next in
currentValue = f(currentValue, next, emit)
}, error: { error in
subscriber.putError(error)
}, completed: {
subscriber.putNext(currentValue)
subscriber.putCompletion()
})
}
}
| mit | 047983df9e501e28c255ce0ed4306beb | 30.588235 | 105 | 0.528864 | 4.178988 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift | Solutions/SolutionsTests/Easy/Easy_014_Longest_Common_Prefix_Test.swift | 4 | 3168 | //
// Easy_014_Longest_Common_Prefix_Test.swift
// Solutions
//
// Created by Wu, Di on 3/30/15.
// Copyright (c) 2015 diwu. All rights reserved.
//
import XCTest
class Easy_014_Longest_Common_Prefix_Test: XCTestCase {
let ProblemName: String = "Easy_014_Longest_Common_Prefix"
func test_001() {
let input: [String] = []
let expected: String = ""
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_002() {
let input: [String] = ["a"]
let expected: String = "a"
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_003() {
let input: [String] = ["a", "b"]
let expected: String = ""
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_004() {
let input: [String] = ["a", "ab"]
let expected: String = "a"
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_005() {
let input: [String] = ["a", "ab", ""]
let expected: String = ""
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_006() {
let input: [String] = ["a", "ab", "c"]
let expected: String = ""
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_007() {
let input: [String] = ["ab", "ab", "ab"]
let expected: String = "ab"
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_008() {
let input: [String] = ["abc", "ab", "ab"]
let expected: String = "ab"
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
func test_009() {
let input: [String] = ["ab", "ab", "abc"]
let expected: String = "ab"
let result: String = Easy_014_Longest_Common_Prefix.longestCommonPrefix(input)
assertHelper(result == expected, problemName: ProblemName,input: input, resultValue: result, expectedValue: expected)
}
} | mit | 0b96818b597be498a15542d5310ee58c | 44.927536 | 125 | 0.653409 | 4.13577 | false | true | false | false |
yunzixun/V2ex-Swift | View/V2RefreshHeader.swift | 1 | 2676 | //
// V2RefreshHeader.swift
// V2ex-Swift
//
// Created by huangfeng on 1/27/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import MJRefresh
class V2RefreshHeader: MJRefreshHeader {
var loadingView:UIActivityIndicatorView?
var arrowImage:UIImageView?
override var state:MJRefreshState{
didSet{
switch state {
case .idle:
self.loadingView?.isHidden = true
self.arrowImage?.isHidden = false
self.loadingView?.stopAnimating()
case .pulling:
self.loadingView?.isHidden = false
self.arrowImage?.isHidden = true
self.loadingView?.startAnimating()
case .refreshing:
self.loadingView?.isHidden = false
self.arrowImage?.isHidden = true
self.loadingView?.startAnimating()
default:
NSLog("")
}
}
}
/**
初始化工作
*/
override func prepare() {
super.prepare()
self.mj_h = 50
self.loadingView = UIActivityIndicatorView(activityIndicatorStyle: .white)
self.addSubview(self.loadingView!)
self.arrowImage = UIImageView(image: UIImage.imageUsedTemplateMode("ic_arrow_downward"))
self.addSubview(self.arrowImage!)
self.themeChangedHandler = {[weak self] (style) -> Void in
if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault {
self?.loadingView?.activityIndicatorViewStyle = .gray
self?.arrowImage?.tintColor = UIColor.gray
}
else{
self?.loadingView?.activityIndicatorViewStyle = .white
self?.arrowImage?.tintColor = UIColor.gray
}
}
}
/**
在这里设置子控件的位置和尺寸
*/
override func placeSubviews(){
super.placeSubviews()
self.loadingView!.center = CGPoint(x: self.mj_w/2, y: self.mj_h/2);
self.arrowImage!.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
self.arrowImage!.center = self.loadingView!.center
}
override func scrollViewContentOffsetDidChange(_ change: [AnyHashable: Any]!) {
super.scrollViewContentOffsetDidChange(change)
}
override func scrollViewContentSizeDidChange(_ change: [AnyHashable: Any]!) {
super.scrollViewContentOffsetDidChange(change)
}
override func scrollViewPanStateDidChange(_ change: [AnyHashable: Any]!) {
super.scrollViewPanStateDidChange(change)
}
}
| mit | 74730e1743c1356462c6724d9171ab88 | 30.023529 | 96 | 0.588168 | 5.090734 | false | false | false | false |
mathewsanders/Tally-Walker | Tally/Tally/CoreData+Extensions.swift | 1 | 15123 | // CoreData+Extensions.swift
//
// Copyright (c) 2016 Mathew Sanders
//
// 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 CoreData
/// Information used with creating a Core Data persistant store.
public enum CoreDataStoreInformation {
case sqliteStore(at: URL)
case binaryStore(at: URL)
case inMemoryStore(at: URL)
/// Physical location of the persistant store
///
/// - mainBundle: the application's main bundle, resources here are read only.
/// - defaultDirectory: the default directory created by NSPersistentContainer, resources here are read/write safe.
/// - directory(at: URL): any other location, caller is responsable for read/write safety of the resource.
public enum Location {
case mainBundle
case defaultDirectory
case directory(at: URL)
}
/// Error raised when using CoreDataStoreInformation
///
/// - mainBundleResourceNotFound:
/// Attempted to initilize `CoreDataStoreInformation` describing a resource within the main
/// bundle that does not exist
enum CoreDataStoreInformationError: Error {
case mainBundleResourceNotFound
}
/// Initializes information for a sqlite resource with a name, extension, and location.
///
/// - Parameters:
/// - resourceName: The name of the resource.
/// - resourceExtension: The extension of the resource, default is 'sqlite'.
/// - location: Location of the resource, default is `Location.defaultDirectory`.
///
/// - Throws: CoreDataStoreInformationError.mainBundleResourceNotFound when attempting to describe a
/// resource in the main bundle that does not exist.
public init(sqliteStoreNamed resourceName: String, with resourceExtension: String = "sqlite", in location: Location = .defaultDirectory) throws {
let url = try CoreDataStoreInformation.url(for: resourceName, extension: resourceExtension, location: location)
self = .sqliteStore(at: url)
}
/// Initializes information for a binary resource with a name, extension, and location.
///
/// - Parameters:
/// - resourceName: The name of the resource.
/// - resourceExtension: The extension of the resource, default is 'binary'.
/// - location: Location of the resource, default is `Location.defaultDirectory`.
///
/// - Throws: CoreDataStoreInformationError.mainBundleResourceNotFound when attempting to describe a resource
/// in the main bundle that does not exist.
public init(binaryStoreNamed resourceName: String, with resourceExtension: String = "binary", in location: Location = .defaultDirectory) throws {
let url = try CoreDataStoreInformation.url(for: resourceName, extension: resourceExtension, location: location)
self = .binaryStore(at: url)
}
public init(memoryStoreNamed resourceName: String, with resourceExtension: String = "memory", in location: Location = .defaultDirectory) throws {
let url = try CoreDataStoreInformation.url(for: resourceName, extension: resourceExtension, location: location)
self = .inMemoryStore(at: url)
}
var type: String {
switch self {
case .binaryStore: return NSBinaryStoreType
case .sqliteStore: return NSSQLiteStoreType
case .inMemoryStore: return NSInMemoryStoreType
}
}
var url: URL {
switch self {
case .binaryStore(let url): return url
case .sqliteStore(let url): return url
case .inMemoryStore(at: let url): return url
}
}
var description: NSPersistentStoreDescription {
let _description = NSPersistentStoreDescription(url: url)
_description.type = type
return _description
}
/// Attempts to safely tear down a persistant store, and remove physical components.
///
/// Throws:
/// - If the if the store can not be safely removed.
/// - When attempting to remove a resource from the mainBundle.
public func destroyExistingPersistantStoreAndFiles() throws {
// items in the application bundle are read only
// sqlite stores are truncated, not deleted
let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel())
try storeCoordinator.destroyPersistentStore(at: url, ofType: type, options: nil)
// in-memory stores have no file, and binary are deleted by `destroyPersistentStore`.
if case .sqliteStore = self {
// attempt to delete sqlite file and assocaited -wal and -shm files
try deleteFileIfExists(fileUrl: url)
try deleteFileIfExists(fileUrl: url.appendingToPathExtension("-wal"))
try deleteFileIfExists(fileUrl: url.appendingToPathExtension("-shm"))
}
}
private func deleteFileIfExists(fileUrl: URL) throws {
if FileManager.default.fileExists(atPath: fileUrl.path) && FileManager.default.isDeletableFile(atPath: fileUrl.path) {
try FileManager.default.removeItem(at: fileUrl)
}
}
private static func url(for resourceName: String, extension resourceExtension: String, location: Location) throws -> URL {
switch location {
case .directory(at: let baseURL):
return baseURL.appendingPathComponent(resourceName).appendingPathExtension(resourceExtension)
case .defaultDirectory:
return NSPersistentContainer.defaultDirectoryURL().appendingPathComponent(resourceName).appendingPathExtension(resourceExtension)
case .mainBundle:
guard let bundleUrl = Bundle.main.url(forResource: resourceName, withExtension: resourceExtension)
else { throw CoreDataStoreInformationError.mainBundleResourceNotFound }
return bundleUrl
}
}
}
fileprivate extension URL {
func appendingToPathExtension(_ string: String) -> URL {
let pathExtension = self.pathExtension + string
return self.deletingPathExtension().appendingPathExtension(pathExtension)
}
}
extension NSManagedObject {
/// Attempts to safely load this object in a new context.
///
/// **Note:** This method may perform I/O to the backing persistant store.
///
/// Will fail in the following situations:
/// - This object does not have a managed object context.
/// - This object has changes, but could not be saved.
/// - The backing persistant store does not have a record of this object.
///
/// Returns: `nil` if this object could not be loaded into the new context, otherwise returns an instance
/// of NSManagedObject in the new context.
func loaded<ManagedObjectType: NSManagedObject>(in context: NSManagedObjectContext) -> ManagedObjectType? {
var object: ManagedObjectType? = nil
guard let originalContext = managedObjectContext
else { return object }
do {
// save to ensure that object id is perminant, and so this node is persisted to store
// and can be obtained by a cousin context
if originalContext.hasChanges {
try originalContext.save()
}
// use object id to load into the new context
// see also: https://medium.com/bpxl-craft/some-lessons-learned-on-core-data-5f095ecb1882#.mzee3j5vf
// TODO: Create an asynchronous version.
context.performAndWait {
do {
object = try context.existingObject(with: self.objectID) as? ManagedObjectType
}
// catch error from loading object from id
catch { print(error) }
}
}
// catch error from saving original context
catch { print(error) }
// if everything has gone without error, this will be the `this` object
// loaded in the new context, otherwise it will be `nil`
return object
}
}
// MARK: - CoreDataStack
internal class CoreDataStack {
let storeContainer: NSPersistentContainer
let mainContext: NSManagedObjectContext
let backgroundContext: NSManagedObjectContext
let storeInformation: CoreDataStoreInformation
init(store storeInformation: CoreDataStoreInformation, fromArchive archive: CoreDataStoreInformation? = nil) throws {
// load the mom
guard let momUrl = Bundle(for: CoreDataStack.self).url(forResource: "TallyStoreModel", withExtension: "momd"),
let mom = NSManagedObjectModel(contentsOf: momUrl)
else { throw CoreDataTallyStoreError.missingModelObjectModel }
var storeLoadError: Error?
// request to load store with contents of an achived store
if let archive = archive {
// if the store already exists, then don't import from the archive
if !FileManager.default.fileExists(atPath: storeInformation.url.path) {
// initalize archive container and load
let archiveContainer = NSPersistentContainer(name: "ArchiveContainer", managedObjectModel: mom)
archiveContainer.persistentStoreDescriptions = [archive.description]
archiveContainer.loadPersistentStores { _, error in storeLoadError = error }
// migrate the archive to the sqlite location
guard let archivedStore = archiveContainer.persistentStoreCoordinator.persistentStore(for: archive.url), storeLoadError == nil
else { throw storeLoadError! }
// Stores archived by CoreDataStack apply manual vacuum and set journal mode to DELETE
// Need to test to see if nil options are passed through the archive options are used
// of if the persistant store coordiantors default options are used instead
/*
let options: [String: Any] = [
NSSQLiteManualVacuumOption: false,
NSSQLitePragmasOption: ["journal_mode": "WAL"]
]
*/
try archiveContainer.persistentStoreCoordinator.migratePersistentStore(archivedStore, to: storeInformation.url, options: nil, withType: storeInformation.type)
}
}
// initalize store container and load
storeContainer = NSPersistentContainer(name: "StoreContainer", managedObjectModel: mom)
storeContainer.persistentStoreDescriptions = [storeInformation.description]
storeContainer.loadPersistentStores { description, error in
storeLoadError = error
print("Store loaded:", description)
}
guard let _ = storeContainer.persistentStoreCoordinator.persistentStore(for: storeInformation.url), storeLoadError == nil
else {
print(storeLoadError as Any)
throw CoreDataTallyStoreError.storeNotLoaded
}
// Assign main context and background context.
//
// Merge policy needs to be set because of unique constraint on literal item managed objects
// `automaticallyMergesChangesFromParent` is set on the main context so that when saves are
// made on the background context, the main context automatically attempts to refresh any objects
// that are currently in context.
self.mainContext = storeContainer.viewContext
mainContext.automaticallyMergesChangesFromParent = true
mainContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
self.backgroundContext = storeContainer.newBackgroundContext()
backgroundContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
self.storeInformation = storeInformation
}
func save(context: NSManagedObjectContext, completed: (() -> Void)? = nil) throws {
var saveError: NSError?
// always perform save in correct thread
context.perform {
// if there are no changes, then return early
guard context.hasChanges else {
completed?()
return
}
// attempt a save, if save fails log and save the error to throw later
do {
try context.save()
}
catch {
print("save error...")
print(error.localizedDescription)
saveError = error as NSError
}
completed?()
}
// if an error was caught, throw it up to the method caller
if let error = saveError {
throw CoreDataTallyStoreError.otherError(error)
}
}
// see: https://developer.apple.com/library/content/qa/qa1809/_index.html
// see: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/PersistentStoreFeatures.html
// see: http://stackoverflow.com/questions/20969996/is-it-safe-to-delete-sqlites-wal-file
func archive(as archiveStore: CoreDataStoreInformation) throws {
guard let currentStore = self.storeContainer.persistentStoreCoordinator.persistentStore(for: storeInformation.url)
else { throw CoreDataTallyStoreError.noStoreToArchive }
let options: [String: Any]? = {
switch archiveStore {
case .sqliteStore:
return [NSSQLitePragmasOption: ["journal_mode": "DELETE"], NSSQLiteManualVacuumOption: true]
default:
return nil
}
}()
try self.storeContainer.persistentStoreCoordinator.migratePersistentStore(currentStore, to: archiveStore.url, options: options, withType: archiveStore.type)
}
}
| mit | 93c867a78a6a2d1df85ab6dcc6113bd9 | 43.875371 | 174 | 0.6545 | 5.566066 | false | false | false | false |
beltex/dshb | dshb/WidgetFan.swift | 1 | 2550 | //
// WidgetFan.swift
// dshb
//
// The MIT License
//
// Copyright (C) 2014-2017 beltex <https://beltex.github.io>
//
// 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.
struct WidgetFan: WidgetType {
let name = "Fan"
let displayOrder = 6
var title: WidgetUITitle
var stats = [WidgetUIStat]()
init(window: Window = Window()) {
title = WidgetUITitle(name: name, window: window)
let fanCount: Int
do { fanCount = try SMCKit.fanCount() }
catch { fanCount = 0 }
for index in 0..<fanCount {
// Not sorting fan names, most will not have more than 2 anyway
let fanName: String
do { fanName = try SMCKit.fanName(index) }
catch { fanName = "Fan \(index)" }
let fanMaxSpeed: Int
do {
fanMaxSpeed = try SMCKit.fanMaxSpeed(index)
} catch {
// Skip this fan
continue
}
stats.append(WidgetUIStat(name: fanName, unit: .RPM,
max: Double(fanMaxSpeed)))
}
}
mutating func draw() {
for index in 0..<stats.count {
do {
let fanSpeed = try SMCKit.fanCurrentSpeed(index)
stats[index].draw(String(fanSpeed),
percentage: Double(fanSpeed) / stats[index].maxValue)
} catch {
stats[index].draw("Error", percentage: 0)
}
}
}
}
| mit | 0954f72c206a3afa49f41974cb4cd71a | 33 | 83 | 0.613333 | 4.419411 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Conversation/ZMConversation+Labels.swift | 1 | 2005 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// 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 Foundation
extension ZMConversation {
@objc
public var isFavorite: Bool {
get {
return labels.any({ $0.kind == .favorite })
}
set {
guard let managedObjectContext = managedObjectContext else { return }
let favoriteLabel = Label.fetchFavoriteLabel(in: managedObjectContext)
if newValue {
assignLabel(favoriteLabel)
} else {
removeLabel(favoriteLabel)
}
}
}
@objc
public var folder: LabelType? {
return labels.first(where: { $0.kind == .folder })
}
@objc
public func moveToFolder(_ folder: LabelType) {
guard let label = folder as? Label, !label.isZombieObject, label.kind == .folder else { return }
removeFromFolder()
assignLabel(label)
}
@objc
public func removeFromFolder() {
let existingFolders = labels.filter({ $0.kind == .folder })
labels.subtract(existingFolders)
for emptyFolder in existingFolders.filter({ $0.conversations.isEmpty}) {
emptyFolder.markForDeletion()
}
}
func assignLabel(_ label: Label) {
labels.insert(label)
}
func removeLabel(_ label: Label) {
labels.remove(label)
}
}
| gpl-3.0 | b77d8c55f00b0ecc4c31772430c7078d | 26.465753 | 104 | 0.633416 | 4.495516 | false | false | false | false |
djbe/AppwiseCore | Sources/Core/Settings.swift | 1 | 3231 | //
// Settings.swift
// AppwiseCore
//
// Created by David Jennes on 17/09/16.
// Copyright © 2019 Appwise. All rights reserved.
//
import CocoaLumberjack
import Foundation
/// This is a light layer over the UserDefaults framework, that'll load any settings you have
/// in a settings bundle, and perform version checks for the `Config`.
public struct Settings {
fileprivate enum DefaultsKey: String {
case reset = "reset_app"
case resourceTimestamps
case version
case lastVersion
}
/// `Settings` is a singleton.
public static var shared = Settings()
/// The underlying user defaults.
public let defaults = UserDefaults.standard
private init() {}
internal mutating func load<C: Config>(with config: C) {
// version check
let new = config.appVersion
if let old = lastVersion, old < new {
config.handleUpdate(from: old, to: new)
}
version = "\(config.appVersion) (\(config.appBuild))"
lastVersion = config.appVersion
// try to load settings bundle
guard let bundle = Bundle.main.path(forResource: "Settings", ofType: "bundle") as NSString?,
let settings = NSDictionary(contentsOfFile: bundle.appendingPathComponent("Root.plist")),
let preferences = settings["PreferenceSpecifiers"] as? [[String: Any]] else {
DDLogError("Could not find Settings.bundle")
return
}
// load defaults from settings bundle
var data = [String: Any]()
for specification in preferences {
guard let key = specification["Key"] as? String,
defaults.object(forKey: key) == nil else { continue }
data[key] = specification["DefaultValue"]
}
defaults.register(defaults: data)
}
internal func reset() {
guard let identifier = Bundle.main.bundleIdentifier else { return }
defaults.removePersistentDomain(forName: identifier)
}
internal var shouldReset: Bool {
get {
return defaults.bool(forKey: DefaultsKey.reset.rawValue)
}
set {
defaults.set(newValue, forKey: DefaultsKey.reset.rawValue)
}
}
private var version: String? {
get {
return defaults.string(forKey: DefaultsKey.version.rawValue)
}
set {
defaults.set(newValue, forKey: DefaultsKey.version.rawValue)
}
}
private var lastVersion: Version? {
get {
// fallback to readable version if needed
let string = defaults.string(forKey: DefaultsKey.lastVersion.rawValue) ??
version?.components(separatedBy: " ").first
return string.flatMap(Version.init(string:))
}
set {
defaults.set(newValue?.description ?? "", forKey: DefaultsKey.lastVersion.rawValue)
}
}
}
extension Settings {
func key<R: Router>(router: R) -> String {
return "\(router.method)|\(R.baseURLString)|\(router.path)"
}
func timestamp<R: Router>(router: R) -> TimeInterval {
guard let timestamps = defaults.dictionary(forKey: DefaultsKey.resourceTimestamps.rawValue) as? [String: Double] else {
return 0
}
return timestamps[key(router: router)] ?? 0
}
func setTimestamp<R: Router>(_ timestamp: TimeInterval, router: R) {
var timestamps = defaults.dictionary(forKey: DefaultsKey.resourceTimestamps.rawValue) as? [String: Double] ?? [String: Double]()
timestamps[key(router: router)] = timestamp
defaults.set(timestamps, forKey: DefaultsKey.resourceTimestamps.rawValue)
}
}
| mit | 3df9af342c18ddb35c6579e9a10d0aa2 | 28.633028 | 130 | 0.714551 | 3.760186 | false | true | false | false |
goldenplan/Pattern-on-Swift | Mediator.playground/Contents.swift | 1 | 1795 | //: Playground - noun: a place where people can play
// Mediator pattern
import Cocoa
protocol Mediator{
func send(message: String, colleague: Colleague)
}
class Colleague{
var mediator: Mediator!
init(mediator: Mediator) {
self.mediator = mediator
}
}
class ConcreteMediator: Mediator{
var concreteColleagueFirst: ConcreteColleagueFirst!
var concreteColleagueSecond: ConcreteColleagueSecond!
func send(message: String, colleague: Colleague) {
if colleague is ConcreteColleagueFirst{
concreteColleagueSecond.notify(message: message)
}else{
concreteColleagueFirst.notify(message: message)
}
}
}
class ConcreteColleagueFirst:Colleague{
override init(mediator: Mediator) {
super.init(mediator: mediator)
}
func send(message: String){
mediator.send(message: message, colleague: self)
}
func notify(message: String){
print("First got: ", message)
}
}
class ConcreteColleagueSecond:Colleague{
override init(mediator: Mediator) {
super.init(mediator: mediator)
}
func send(message: String){
mediator.send(message: message, colleague: self)
}
func notify(message: String){
print("Second got: ", message)
}
}
let concreteMediator = ConcreteMediator()
let concreteColleagueFirst = ConcreteColleagueFirst(mediator: concreteMediator)
let concreteColleagueSecond = ConcreteColleagueSecond(mediator: concreteMediator)
concreteMediator.concreteColleagueFirst = concreteColleagueFirst
concreteMediator.concreteColleagueSecond = concreteColleagueSecond
concreteColleagueFirst.send(message: "Hi Second!")
concreteColleagueSecond.send(message: "Hi First!")
| mit | 9e12a5e52fcd747a72e4c81fc30c6728 | 22.933333 | 81 | 0.695822 | 4.812332 | false | false | false | false |
yourtion/RestfulClient | RestClient/ParamViewController.swift | 1 | 1570 | //
// ParamViewController.swift
// RestClient
//
// Created by YourtionGuo on 7/22/14.
// Copyright (c) 2014 yourtion. All rights reserved.
//
import UIKit
class ParamViewController: UIViewController {
@IBOutlet var paramKey: UITextField!
@IBOutlet var paramValue: UITextView!
@IBOutlet var doneBtn: UIBarButtonItem!
var param = []
var edit = false
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Param"
}
override func viewWillAppear(animated: Bool) {
if (param.count > 0){
paramKey.text = param[0] as? String
paramValue.text = param[1] as! String
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doneParam(sender: UIBarButtonItem) {
if (paramKey.hasText() && paramValue.hasText()){
print("Done")
let requestView:RequestViewController = navigationController!.viewControllers[navigationController!.viewControllers.count - 2] as! RequestViewController
let key :String = paramKey.text!
let value :String = paramValue.text!
if (edit){
requestView.params[requestView.editingIndex] = [key, value]
}else{
requestView.params.append([key, value])
}
requestView.paramTable.reloadData()
navigationController!.popViewControllerAnimated(true)
}
}
}
| mit | 1f0e55127d1ff17f3471c14a680508e9 | 28.074074 | 164 | 0.621019 | 4.875776 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/MaskDesignable.swift | 5 | 9379 | //
// Created by Jake Lin on 12/13/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
/// A protocol provides mask designable feature.
public protocol MaskDesignable {
/**
The type of the mask used for masking an IBAnimatable UI element.
When you create a class and conform to `MaskDesignable`, you need to implement this computed property like
```
public var maskType: MaskType = .none {
didSet {
configureMask()
configureBorder()
}
}
```
Because Interface Builder doesn't support `enum` for `@IBInspectable` property. You need to create an `internal` property using optional String as the type like
```
@IBInspectable var _maskType: String? {
didSet {
maskType = MaskType(string: _maskType)
}
}
```
*/
var maskType: MaskType { get set }
}
public extension MaskDesignable where Self: UIView {
/// Mask the IBAnimatable UI element with provided `maskType`
public func configureMask() {
switch maskType {
case .circle:
maskCircle()
case .parallelogram(let angle):
maskParallelogram(with: angle)
case .polygon(let sides):
maskPolygon(with: sides)
case .star(let points):
maskStar(with: points )
case .wave(let direction, let width, let offset):
maskWave(with: direction, width: width, offset: offset)
case .triangle:
maskTriangle()
case .none:
layer.mask?.removeFromSuperlayer()
}
}
}
// MARK: - Private mask functions
private extension MaskDesignable where Self: UIView {
// MARK: - Circle
/// Mask a circle shape.
func maskCircle() {
let diameter = ceil(min(bounds.width, bounds.height))
let origin = CGPoint(x: (bounds.width - diameter) / 2.0, y: (bounds.height - diameter) / 2.0)
let size = CGSize(width: diameter, height: diameter)
let circlePath = UIBezierPath(ovalIn: CGRect(origin: origin, size: size))
draw(circlePath)
}
// MARK: - Polygon
/**
Mask a polygon shape.
- Parameter sides: The number of the polygon sides.
*/
func maskPolygon(with sides: Int) {
let polygonPath = getPolygonBezierPath(with: max(sides, 3))
draw(polygonPath)
}
/**
Get a Bezier path for a polygon shape with provided sides.
- Parameter sides: The number of the polygon sides.
- Returns: A Bezier path for a polygon shape.
*/
func getPolygonBezierPath(with sides: Int) -> UIBezierPath {
let path = UIBezierPath()
let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
var angle: CGFloat = -.pi / 2
let angleIncrement = .pi * 2 / CGFloat(sides)
let length = min(bounds.width, bounds.height)
let radius = length / 2.0
path.move(to: point(from: angle, radius: radius, offset: center))
for _ in 1...sides - 1 {
angle += angleIncrement
path.addLine(to: point(from: angle, radius: radius, offset: center))
}
path.close()
return path
}
// MARK: - Star
/**
Mask a star shape.
- Parameter points: The number of the star points.
*/
func maskStar(with points: Int) {
// FIXME: Do not mask the shadow.
// Stars must has at least 3 points.
var starPoints = points
if points <= 2 {
starPoints = 5
}
let path = getStarPath(with: starPoints)
draw(path)
}
/**
Get a Bezier path for a star shape with provided points.
- Parameter sides: The number of the star points.
- Returns: A Bezier path for a star shape.
*/
func getStarPath(with points: Int, borderWidth: CGFloat = 0) -> UIBezierPath {
let path = UIBezierPath()
let radius = min(bounds.size.width, bounds.size.height) / 2 - borderWidth
let starExtrusion = radius / 2
let angleIncrement = .pi * 2 / CGFloat(points)
let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
var angle: CGFloat = -.pi / 2
for _ in 1...points {
let aPoint = point(from: angle, radius: radius, offset: center)
let nextPoint = point(from: angle + angleIncrement, radius: radius, offset: center)
let midPoint = point(from: angle + angleIncrement / 2.0, radius: starExtrusion, offset: center)
if path.isEmpty {
path.move(to: aPoint)
}
path.addLine(to: midPoint)
path.addLine(to: nextPoint)
angle += angleIncrement
}
path.close()
return path
}
// MARK: - Parallelogram
/**
Mask a parallelogram shape with provided top-left angle.
- Parameter topLeftAngle: The top-left angle of the parallelogram shape.
*/
func maskParallelogram(with topLeftAngle: Double) {
let parallelogramPath = getParallelogramBezierPath(with: topLeftAngle)
draw(parallelogramPath)
}
/**
Get a Bezier path for a parallelogram shape with provided top-left angle.
- Parameter sides: The top-left angle of the parallelogram shape.
- Returns: A Bezier path for a parallelogram shape.
*/
func getParallelogramBezierPath(with topLeftAngle: Double) -> UIBezierPath {
let topLeftAngleRad = topLeftAngle * .pi / 180
let path = UIBezierPath()
let offset = abs(CGFloat(tan(topLeftAngleRad - .pi / 2)) * bounds.height)
if topLeftAngle <= 90 {
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: bounds.width - offset, y: 0))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
path.addLine(to: CGPoint(x: offset, y: bounds.height))
} else {
path.move(to: CGPoint(x: offset, y: 0))
path.addLine(to: CGPoint(x: bounds.width, y: 0))
path.addLine(to: CGPoint(x: bounds.width - offset, y: bounds.height))
path.addLine(to: CGPoint(x: 0, y: bounds.height))
}
path.close()
return path
}
// MARK: - Triangle
/**
Mask a triangle shape.
*/
func maskTriangle() {
let trianglePath = getTriangleBezierPath()
draw(trianglePath)
}
/**
Get a Bezier path for a triangle shape.
- Returns: A Bezier path for a triangle shape.
*/
func getTriangleBezierPath() -> UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.width / 2.0, y: bounds.origin.y))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
path.addLine(to: CGPoint(x: bounds.origin.x, y: bounds.height))
path.close()
return path
}
// MARK: - Wave
/**
Mask a wave shape with provided prameters.
- Parameter direction: The direction of the wave shape.
- Parameter width: The width of the wave shape.
- Parameter offset: The offset of the wave shape.
*/
func maskWave(with direction: MaskType.WaveDirection, width: Double, offset: Double) {
let wavePath = getWaveBezierPath(with: direction == .up, width: CGFloat(width), offset: CGFloat(offset))
draw(wavePath)
}
/**
Get a Bezier path for a parallelogram wave with provided prameters.
- Parameter isUp: The flag to indicate whether the wave is up or not.
- Parameter width: The width of the wave shape.
- Parameter offset: The offset of the wave shape.
- Returns: A Bezier path for a wave shape.
*/
func getWaveBezierPath(with isUp: Bool, width: CGFloat, offset: CGFloat) -> UIBezierPath {
let originY = isUp ? bounds.maxY : bounds.minY
let halfWidth = width / 2.0
let halfHeight = bounds.height / 2.0
let quarterWidth = width / 4.0
var isUp = isUp
var startX = bounds.minX - quarterWidth - (offset.truncatingRemainder(dividingBy: width))
var endX = startX + halfWidth
let path = UIBezierPath()
path.move(to: CGPoint(x: startX, y: originY))
path.addLine(to: CGPoint(x: startX, y: bounds.midY))
repeat {
path.addQuadCurve(
to: CGPoint(x: endX, y: bounds.midY),
controlPoint: CGPoint(
x: startX + quarterWidth,
y: isUp ? bounds.maxY + halfHeight : bounds.minY - halfHeight)
)
startX = endX
endX += halfWidth
isUp = !isUp
} while startX < bounds.maxX
path.addLine(to: CGPoint(x: path.currentPoint.x, y: originY))
return path
}
}
// MARK: - Private helper functions
private extension MaskDesignable where Self: UIView {
/**
Draw a Bezier path on `layer.mask` using `CAShapeLayer`.
- Parameter path: The Bezier path to draw.
*/
func draw(_ path: UIBezierPath) {
layer.mask?.removeFromSuperlayer()
let maskLayer = CAShapeLayer()
maskLayer.frame = CGRect(origin: .zero, size: bounds.size)
maskLayer.path = path.cgPath
layer.mask = maskLayer
}
/**
Return a radian from a provided degree a Bezier path on `layer.mask` using `CAShapeLayer`.
- Parameter degree: The degree to convert.
- Returns: A radian converted from the provided degree.
*/
func degree2radian(degree: CGFloat) -> CGFloat {
return .pi * degree / 180
}
/**
Return a CGPoint from provided parameters.
- Parameter angle: The angle to determine a point.
- Parameter radius: The radius to determine a point.
- Parameter offset: The offset to determine a point.
- Returns: A CGPoint based on provided parameters.
*/
func point(from angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint {
return CGPoint(x: radius * cos(angle) + offset.x, y: radius * sin(angle) + offset.y)
}
}
| gpl-3.0 | 2a823697849d4f999ff92e1195f00604 | 28.961661 | 163 | 0.64694 | 4.028351 | false | false | false | false |
Jvaeyhcd/NavTabBarController | NavTabBarControllerDemo/NavTabBarControllerDemo/SlippedTableViewController.swift | 1 | 2008 | //
// SlippedTableViewController.swift
// NavTabBarControllerDemo
//
// Created by Jvaeyhcd on 21/04/2017.
// Copyright © 2017 Jvaeyhcd. All rights reserved.
//
import UIKit
class SlippedTableViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), style: .plain)
tableView.register(SlippedTableViewCell.self, forCellReuseIdentifier: "SlippedTableViewCell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SlippedTableViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SlippedTableViewCell", for: indexPath) as! SlippedTableViewCell
cell.textLabel?.text = "Item\(indexPath.row + 1)"
return cell
}
}
| mit | 8a17af4ba572b24335d99efe4d49a3f3 | 30.359375 | 129 | 0.683607 | 5.004988 | false | false | false | false |
PrestonV/ios-cannonball | Cannonball/PoemComposerViewController.swift | 1 | 12990 | //
// Copyright (C) 2014 Twitter, Inc. and other contributors.
//
// 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 QuartzCore
class PoemComposerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ImageCarouselDataSource, CountdownViewDelegate {
var theme: Theme! {
didSet {
// Randomize the order of pictures.
self.themePictures = theme.pictures.sorted { (_, _) in arc4random() < arc4random() }
}
}
// MARK: Properties
private var poem: Poem
private var themePictures: [String] = []
private var bankWords: [String] = []
private let countdownView: CountdownView
private let wordCount = 20
private let timeoutSeconds = 60
@IBOutlet private weak var doneButton: UIBarButtonItem!
@IBOutlet private weak var shuffleButton: UIButton!
@IBOutlet private weak var bankCollectionView: UICollectionView!
@IBOutlet private weak var poemCollectionView: UICollectionView!
@IBOutlet private weak var poemHeightContraint: NSLayoutConstraint!
@IBOutlet private weak var imageCarousel: ImageCarouselView!
// MARK: IBActions
@IBAction func shuffleWordBank() {
refreshWordBank()
bankCollectionView.reloadData()
}
// MARK: View Life Cycle
required init(coder aDecoder: NSCoder) {
self.countdownView = CountdownView(frame: CGRect(x: 0, y: 0, width: 40, height: 40), countdownTime: timeoutSeconds)
self.poem = Poem()
super.init(coder: aDecoder)
self.countdownView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// Trigger a first word bank refresh to retrieve a selection of words.
bankCollectionView.clipsToBounds = false
refreshWordBank()
// Customize the navigation bar.
self.navigationItem.rightBarButtonItem?.enabled = false
self.navigationController?.navigationBar.translucent = true
// Add the countdown view.
countdownView.frame.origin.x = (self.view.frame.size.width - countdownView.frame.size.width) / 2
countdownView.frame.origin.y = -countdownView.frame.size.height - 10
self.navigationController?.view.addSubview(countdownView)
self.navigationController?.view.bringSubviewToFront(countdownView)
countdownView.countdownTime = timeoutSeconds
imageCarousel.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Make sure the navigation bar is translucent.
self.navigationController?.navigationBar.translucent = true
// Animate the countdown to make it appear and start the timer when the view appears.
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: { () -> Void in
// Place the countdown frame at the correct origin position.
self.countdownView.frame.origin.y = 10
}) { (finished) -> Void in
self.countdownView.start()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.countdownView.stop()
// Animate the countdown off screen.
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: { () -> Void in
// Place the frame at the correct origin position.
self.countdownView.frame.origin.y = -self.countdownView.frame.size.height - 10
}, completion: nil)
}
// MARK: UIStoryboardSegue Handling
// Only perform the segue to the history if there is a composed poem.
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if identifier == "ShowHistory" {
return poem.words.count > 0
}
return true
}
// Prepare for the segue to the history.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Save the poem.
savePoem()
}
// MARK: CountdownViewDelegate
func countdownView(countdownView: CountdownView, didCountdownTo second: Int) {
switch(second) {
case 0:
if poem.words.count > 0 {
// Perform the segue to go the poem history.
self.performSegueWithIdentifier("ShowHistory", sender: self.countdownView)
} else {
// Go back to the theme chooser.
self.navigationController?.popViewControllerAnimated(true)
}
case 10:
// Change the color of Shuffle to red as well.
shuffleButton.setTitleColor(UIColor(red: 238/255, green: 103/255, blue: 100/255, alpha: 1.0), forState: .Normal)
default:
break
}
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == bankCollectionView {
return bankWords.count
} else if collectionView == poemCollectionView {
return poem.words.count
}
return 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PoemComposerWordCell", forIndexPath: indexPath) as PoemComposerWordCell
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
var word = ""
if collectionView == bankCollectionView {
word = bankWords[indexPath.row]
} else if collectionView == poemCollectionView {
word = poem.words[indexPath.row]
}
// Inject the word in the cell.
cell.word.text = word
cell.word.frame = cell.bounds
// Draw the border using the same color as the word.
cell.layer.masksToBounds = false
cell.layer.borderColor = cell.word.textColor.CGColor
cell.layer.borderWidth = 2
cell.layer.cornerRadius = 3
// Add a subtle opacity to poem words for better readability on top of pictures.
if collectionView == poemCollectionView {
cell.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2)
}
// Make sure the cell is not hidden.
cell.hidden = false
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int {
return 1
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// A word in the bank has been tapped.
if collectionView == bankCollectionView {
// Fade out and hide the word in the bank.
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: { () -> Void in
cell.alpha = 0
}) { (finished) -> Void in
cell.hidden = true
}
}
// Add the word to the poem.
let word = bankWords[indexPath.row]
poem.words.append(word)
// Display the word in the poem.
displayWord(word, inCollectionView: poemCollectionView)
// A word in the poem has been tapped.
} else if collectionView == poemCollectionView {
// Fade out then remove the word from the poem.
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
UIView.animateWithDuration(0.15, animations: { () -> Void in
cell.alpha = 0
}) { (finished) -> Void in
collectionView.performBatchUpdates({
collectionView.deleteItemsAtIndexPaths([indexPath])
}, completion: { _ in
self.resizePoemToFitContentSize()
cell.alpha = 1
})
}
}
// Display the word back in the bank.
let word = poem.words[indexPath.row]
displayWord(word, inCollectionView: bankCollectionView)
// Remove the word from the poem.
poem.words.removeAtIndex(indexPath.row)
}
// Update the tick icon state.
self.navigationItem.rightBarButtonItem?.enabled = poem.words.count > 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var word = ""
if collectionView == bankCollectionView {
word = bankWords[indexPath.row]
} else if collectionView == poemCollectionView {
word = poem.words[indexPath.row]
}
return sizeForWord(word)
}
// MARK: UICollectionView Utilities
func sizeForWord(word: String) -> CGSize {
return CGSize(width: 18 + countElements(word) * 10, height: 32)
}
func resizePoemToFitContentSize() {
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.poemHeightContraint.constant = self.poemCollectionView.contentSize.height
self.view.layoutIfNeeded()
})
}
func savePoem() {
// Save the poem current completion date.
poem.date = NSDate()
// Save the theme name for the poem.
poem.theme = theme.name
// Save the currently displayed picture.
poem.picture = self.themePictures[self.imageCarousel.currentImageIndex]
PoemPersistence.sharedInstance.persistPoem(self.poem)
}
func refreshWordBank() {
bankWords = theme.getRandomWords(wordCount - poem.words.count) as [String]
}
func displayWord(word: String, inCollectionView collectionView: UICollectionView!) {
if collectionView == bankCollectionView {
for (index, bankWord) in enumerate(bankWords) {
// Look for the word in the word bank.
if word == bankWord {
// Find the corresponding cell in the collection view and unhide it.
if let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) {
if cell.hidden {
// Unhide and animate the cell again.
cell.hidden = false
UIView.animateWithDuration(0.15, animations: { () -> Void in
cell.alpha = 1
})
// Return since we found it.
return
}
}
}
}
// The word has not been found because a shuffle likely happened, so append it again.
bankWords.append(word)
collectionView.reloadData()
} else if collectionView == poemCollectionView {
// Retrieve the index path of the last word of the poem.
let poemIndexPath = NSIndexPath(forItem: poem.words.count - 1, inSection: 0)
// Insert the cell for this word.
collectionView.performBatchUpdates({
collectionView.insertItemsAtIndexPaths([poemIndexPath])
}, completion: { _ in
self.resizePoemToFitContentSize()
})
// Fade in so it appears more smoothly.
if let cell = collectionView.cellForItemAtIndexPath(poemIndexPath) {
cell.alpha = 0
UIView.animateWithDuration(0.15, animations: { () -> Void in
cell.alpha = 1
})
}
}
}
// MARK: ImageCarouselViewDelegate
func numberOfImagesInImageCarousel(imageCarousel: ImageCarouselView) -> Int {
return countElements(self.themePictures)
}
func imageCarousel(imageCarousel: ImageCarouselView, imageAtIndex index: Int) -> UIImage {
return UIImage(named: self.themePictures[index])!
}
}
| apache-2.0 | a4b9c6619baecf98d8c2e520fde9679a | 36.87172 | 169 | 0.625096 | 5.325953 | false | false | false | false |
lieven/fietsknelpunten-ios | FietsknelpuntenAPI/API+Jurisdiction.swift | 1 | 1455 | //
// API+Jurisdiction.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 28/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import Foundation
extension API
{
public func getAllJurisdictions(completion: @escaping (Bool, [Jurisdiction]?, Error?)->())
{
sendRequest(action: "allJurisdictions", arguments: [:])
{
(success, response, error) in
if success, let jurisdictionDicts = response as? [Any]
{
var jurisdictions = [Jurisdiction]()
for jurisdictionDict in jurisdictionDicts
{
if let jurisdictionDict = jurisdictionDict as? [String: Any], let jurisdiction = Jurisdiction(dictionary: jurisdictionDict)
{
jurisdictions.append(jurisdiction)
}
}
completion(true, jurisdictions, nil)
}
else
{
completion(false, nil, error)
}
}
}
}
extension Jurisdiction
{
internal init?(dictionary: [String: Any])
{
guard let identifier = dictionary.string(forKey: "id", allowConversion: true, defaultValue: nil),
let name = dictionary["name"] as? String,
let countryCode = dictionary["country"] as? String,
let postalCodes = dictionary["postalcodes"] as? [String]
else
{
return nil
}
let info = dictionary["description"] as? String;
let types = dictionary["types"] as? [String]
self.init(identifier: identifier, name: name, countryCode: countryCode, postalCodes: postalCodes, info: info, types: types)
}
}
| mit | 8c5054d324efff8cd425f320792ee7e0 | 22.451613 | 128 | 0.677442 | 3.64411 | false | false | false | false |
shajrawi/swift | test/attr/attr_dynamic_member_lookup.swift | 2 | 19352 | // RUN: %target-typecheck-verify-swift
var global = 42
@dynamicMemberLookup
struct Gettable {
subscript(dynamicMember member: StaticString) -> Int {
return 42
}
}
@dynamicMemberLookup
struct Settable {
subscript(dynamicMember member: StaticString) -> Int {
get {return 42}
set {}
}
}
@dynamicMemberLookup
struct MutGettable {
subscript(dynamicMember member: StaticString) -> Int {
mutating get {
return 42
}
}
}
@dynamicMemberLookup
struct NonMutSettable {
subscript(dynamicMember member: StaticString) -> Int {
get { return 42 }
nonmutating set {}
}
}
func test(a: Gettable, b: Settable, c: MutGettable, d: NonMutSettable) {
global = a.wyverns
a.flavor = global // expected-error {{cannot assign to property: 'a' is a 'let' constant}}
global = b.flavor
b.universal = global // expected-error {{cannot assign to property: 'b' is a 'let' constant}}
b.thing += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a 'let' constant}}
var bm = b
global = bm.flavor
bm.universal = global
bm.thing += 1
var cm = c
global = c.dragons // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
global = c[dynamicMember: "dragons"] // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
global = cm.dragons
c.woof = global // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
var dm = d
global = d.dragons // ok
global = dm.dragons // ok
d.woof = global // ok
dm.woof = global // ok
}
func testIUO(a: Gettable!, b: Settable!) {
global = a.wyverns
a.flavor = global // expected-error {{cannot assign through dynamic lookup property: 'a' is a 'let' constant}}
global = b.flavor
b.universal = global // expected-error {{cannot assign through dynamic lookup property: 'b' is a 'let' constant}}
var bm: Settable! = b
global = bm.flavor
bm.universal = global
}
//===----------------------------------------------------------------------===//
// Returning a function
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct FnTest {
subscript(dynamicMember member: StaticString) -> (Int) -> () {
return { x in () }
}
}
func testFunction(x: FnTest) {
x.phunky(12)
}
func testFunctionIUO(x: FnTest!) {
x.flavor(12)
}
//===----------------------------------------------------------------------===//
// Explicitly declared members take precedence
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct Dog {
public var name = "Kaylee"
subscript(dynamicMember member: String) -> String {
return "Zoey"
}
}
func testDog(person: Dog) -> String {
return person.name + person.otherName
}
//===----------------------------------------------------------------------===//
// Returning an IUO
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct IUOResult {
subscript(dynamicMember member: StaticString) -> Int! {
get { return 42 }
nonmutating set {}
}
}
func testIUOResult(x: IUOResult) {
x.foo?.negate() // Test mutating writeback.
let _: Int = x.bar // Test implicitly forced optional
let b = x.bar
// expected-note@-1{{short-circuit}}
// expected-note@-2{{coalesce}}
// expected-note@-3{{force-unwrap}}
let _: Int = b // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
}
//===----------------------------------------------------------------------===//
// Error cases
//===----------------------------------------------------------------------===//
// Subscript index must be ExpressibleByStringLiteral.
@dynamicMemberLookup
struct Invalid1 {
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a keypath}}
subscript(dynamicMember member: Int) -> Int {
return 42
}
}
// Subscript may not be variadic.
@dynamicMemberLookup
struct Invalid2 {
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid2' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a keypath}}
subscript(dynamicMember member: String...) -> Int {
return 42
}
}
// References to overloads are resolved just like normal subscript lookup:
// they are either contextually disambiguated or are invalid.
@dynamicMemberLookup
struct Ambiguity {
subscript(dynamicMember member: String) -> Int {
return 42
}
subscript(dynamicMember member: String) -> Float {
return 42
}
}
func testAmbiguity(a: Ambiguity) {
let _: Int = a.flexibility
let _: Float = a.dynamism
_ = a.dynamism // expected-error {{ambiguous use of 'subscript(dynamicMember:)'}}
}
// expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}}
@dynamicMemberLookup
extension Int {
subscript(dynamicMember member: String) -> Int {
fatalError()
}
}
// expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}}
@dynamicMemberLookup
func NotAllowedOnFunc() {}
// @dynamicMemberLookup cannot be declared on a base class and fulfilled with a
// derived class.
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'InvalidBase' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a keypath}}
@dynamicMemberLookup
class InvalidBase {}
class InvalidDerived : InvalidBase { subscript(dynamicMember: String) -> Int { get {}} }
// expected-error @+1 {{value of type 'InvalidDerived' has no member 'dynamicallyLookedUp'}}
_ = InvalidDerived().dynamicallyLookedUp
//===----------------------------------------------------------------------===//
// Existentials
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
protocol DynamicProtocol {
subscript(dynamicMember member: StaticString) -> DynamicProtocol {
get nonmutating set
}
}
struct MyDynamicStruct : DynamicProtocol {
subscript(dynamicMember member: StaticString) -> DynamicProtocol {
get { fatalError() }
nonmutating set {}
}
}
func testMutableExistential(a: DynamicProtocol,
b: MyDynamicStruct) -> DynamicProtocol {
a.x.y = b
b.x.y = b
return a.foo.bar.baz
}
// Verify protocol compositions and protocol refinements work.
protocol SubDynamicProtocol : DynamicProtocol {}
typealias ProtocolComp = AnyObject & DynamicProtocol
func testMutableExistential2(a: AnyObject & DynamicProtocol,
b: SubDynamicProtocol,
c: ProtocolComp & AnyObject) {
a.x.y = b
b.x.y = b
c.x.y = b
}
@dynamicMemberLookup
protocol ProtoExt {}
extension ProtoExt {
subscript(dynamicMember member: String) -> String {
get {}
}
}
extension String: ProtoExt {}
func testProtoExt() -> String {
let str = "test"
return str.sdfsdfsdf
}
//===----------------------------------------------------------------------===//
// JSON example
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
enum JSON {
case IntValue(Int)
case StringValue(String)
case ArrayValue(Array<JSON>)
case DictionaryValue(Dictionary<String, JSON>)
var stringValue: String? {
if case .StringValue(let str) = self {
return str
}
return nil
}
subscript(index: Int) -> JSON? {
if case .ArrayValue(let arr) = self {
return index < arr.count ? arr[index] : nil
}
return nil
}
subscript(key: String) -> JSON? {
if case .DictionaryValue(let dict) = self {
return dict[key]
}
return nil
}
subscript(dynamicMember member: String) -> JSON? {
if case .DictionaryValue(let dict) = self {
return dict[member]
}
return nil
}
}
func testJsonExample(x: JSON) -> String? {
_ = x.name?.first
return x.name?.first?.stringValue
}
//===----------------------------------------------------------------------===//
// Class inheritance tests
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
class BaseClass {
subscript(dynamicMember member: String) -> Int {
return 42
}
}
class DerivedClass : BaseClass {}
func testDerivedClass(x: BaseClass, y: DerivedClass) -> Int {
return x.life - y.the + x.universe - y.and + x.everything
}
// Test that derived classes can add a setter.
class DerivedClassWithSetter : BaseClass {
override subscript(dynamicMember member: String) -> Int {
get { return super[dynamicMember: member] }
set {}
}
}
func testOverrideSubscript(a: BaseClass, b: DerivedClassWithSetter) {
let x = a.frotz + b.garbalaz
b.baranozo = x
a.balboza = 12 // expected-error {{cannot assign to property}}
}
//===----------------------------------------------------------------------===//
// Generics
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct SettableGeneric1<T> {
subscript(dynamicMember member: StaticString) -> T? {
get {}
nonmutating set {}
}
}
func testGenericType<T>(a: SettableGeneric1<T>, b: T) -> T? {
a.dfasdf = b
return a.dfsdffff
}
func testConcreteGenericType(a: SettableGeneric1<Int>) -> Int? {
a.dfasdf = 42
return a.dfsdffff
}
@dynamicMemberLookup
struct SettableGeneric2<T> {
subscript<U: ExpressibleByStringLiteral>(dynamicMember member: U) -> T {
get {}
nonmutating set {}
}
}
func testGenericType2<T>(a: SettableGeneric2<T>, b: T) -> T? {
a[dynamicMember: "fasdf"] = b
a.dfasdf = b
return a.dfsdffff
}
func testConcreteGenericType2(a: SettableGeneric2<Int>) -> Int? {
a.dfasdf = 42
return a.dfsdffff
}
// SR-8077 test case.
// `subscript(dynamicMember:)` works as a `@dynamicMemberLookup` protocol
// requirement.
@dynamicMemberLookup
protocol GenericProtocol {
associatedtype S: ExpressibleByStringLiteral
associatedtype T
subscript(dynamicMember member: S) -> T { get }
}
@dynamicMemberLookup
class GenericClass<S: ExpressibleByStringLiteral, T> {
let t: T
init(_ t: T) { self.t = t }
subscript(dynamicMember member: S) -> T { return t }
}
func testGenerics<S, T, P: GenericProtocol>(
a: P,
b: AnyObject & GenericClass<S, T>
) where P.S == S, P.T == T {
let _: T = a.wew
let _: T = b.lad
}
//===----------------------------------------------------------------------===//
// Keypaths
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
class KP {
subscript(dynamicMember member: String) -> Int { return 7 }
}
_ = \KP.[dynamicMember: "hi"]
_ = \KP.testLookup
/* KeyPath based dynamic lookup */
struct Point {
var x: Int
let y: Int // expected-note 2 {{change 'let' to 'var' to make it mutable}}
private let z: Int = 0 // expected-note 10 {{declared here}}
}
struct Rectangle {
var topLeft, bottomRight: Point
}
@dynamicMemberLookup
struct Lens<T> {
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
set { obj[keyPath: member] = newValue.obj }
}
}
var topLeft = Point(x: 0, y: 0)
var bottomRight = Point(x: 10, y: 10)
var lens = Lens(Rectangle(topLeft: topLeft,
bottomRight: bottomRight))
_ = lens.topLeft
_ = lens.topLeft.x
_ = lens.topLeft.y
_ = lens.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = lens.bottomRight
_ = lens.bottomRight.x
_ = lens.bottomRight.y
_ = lens.bottomRight.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<Point>.x
_ = \Lens<Point>.y
_ = \Lens<Point>.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<Rectangle>.topLeft.x
_ = \Lens<Rectangle>.topLeft.y
_ = \Lens<Rectangle>.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<[Int]>.count
_ = \Lens<[Int]>.[0]
_ = \Lens<[[Int]]>.[0].count
lens.topLeft = Lens(Point(x: 1, y: 2)) // Ok
lens.bottomRight.x = Lens(11) // Ok
lens.bottomRight.y = Lens(12) // expected-error {{cannot assign to property: 'y' is a 'let' constant}}
lens.bottomRight.z = Lens(13) // expected-error {{'z' is inaccessible due to 'private' protection level}}
func acceptKeyPathDynamicLookup(_: Lens<Int>) {}
acceptKeyPathDynamicLookup(lens.topLeft.x)
acceptKeyPathDynamicLookup(lens.topLeft.y)
acceptKeyPathDynamicLookup(lens.topLeft.z) // expected-error {{'z' is inaccessible due to 'private' protection level}}
var tupleLens = Lens<(String, Int)>(("ultimate question", 42))
_ = tupleLens.0.count
_ = tupleLens.1
var namedTupleLens = Lens<(question: String, answer: Int)>((question: "ultimate question", answer: 42))
_ = namedTupleLens.question.count
_ = namedTupleLens.answer
@dynamicMemberLookup
class A<T> {
var value: T
init(_ v: T) {
self.value = v
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
get { return value[keyPath: member] }
}
}
// Let's make sure that keypath dynamic member lookup
// works with inheritance
class B<T> : A<T> {}
func bar(_ b: B<Point>) {
let _: Int = b.x
let _ = b.y
let _: Float = b.y // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}}
let _ = b.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
// Existentials and IUOs
@dynamicMemberLookup
protocol KeyPathLookup {
associatedtype T
var value: T { get }
subscript(dynamicMember member: KeyPath<T, Int>) -> Int! { get }
}
extension KeyPathLookup {
subscript(dynamicMember member: KeyPath<T, Int>) -> Int! {
get { return value[keyPath: member] }
}
}
class C<T> : KeyPathLookup {
var value: T
init(_ v: T) {
self.value = v
}
}
func baz(_ c: C<Point>) {
let _: Int = c.x
let _ = c.y
let _: Float = c.y // expected-error {{cannot convert value of type 'Int?' to specified type 'Float'}}
let _ = c.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
@dynamicMemberLookup
class D<T> {
var value: T
init(_ v: T) {
self.value = v
}
subscript<U: Numeric>(dynamicMember member: KeyPath<T, U>) -> (U) -> U {
get { return { offset in self.value[keyPath: member] + offset } }
}
}
func faz(_ d: D<Point>) {
let _: Int = d.x(42)
let _ = d.y(1 + 0)
let _: Float = d.y(1 + 0) // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}}
let _ = d.z(1 + 0) // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
@dynamicMemberLookup
struct SubscriptLens<T> {
var value: T
var counter: Int = 0
subscript(foo: String) -> Int {
get { return 42 }
}
subscript(offset: Int) -> Int {
get { return counter }
set { counter = counter + newValue }
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U! {
get { return value[keyPath: member] }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return value[keyPath: member] }
set { value[keyPath: member] = newValue }
}
}
func keypath_with_subscripts(_ arr: SubscriptLens<[Int]>,
_ dict: inout SubscriptLens<[String: Int]>) {
_ = arr[0..<3]
for idx in 0..<arr.count {
let _ = arr[idx]
print(arr[idx])
}
_ = arr["hello"] // Ok
_ = dict["hello"] // Ok
_ = arr["hello"] = 42 // expected-error {{cannot assign through subscript: subscript is get-only}}
_ = dict["hello"] = 0 // Ok
_ = arr[0] = 42 // expected-error {{cannot assign through subscript: 'arr' is a 'let' constant}}
_ = dict[0] = 1 // Ok
if let index = dict.value.firstIndex(where: { $0.value == 42 }) {
let _ = dict[index]
}
dict["ultimate question"] = 42
}
func keypath_with_incorrect_return_type(_ arr: Lens<Array<Int>>) {
for idx in 0..<arr.count {
// expected-error@-1 {{binary operator '..<' cannot be applied to operands of type 'Int' and 'Lens<Int>'}}
// expected-note@-2 {{expected an argument list of type '(Self, Self)'}}
let _ = arr[idx]
}
}
struct WithTrailingClosure {
subscript(fn: () -> Int) -> Int {
get { return fn() }
nonmutating set { _ = fn() + newValue }
}
subscript(offset: Int, _ fn: () -> Int) -> Int {
get { return offset + fn() }
}
}
func keypath_with_trailing_closure_subscript(_ ty: inout SubscriptLens<WithTrailingClosure>) {
_ = ty[0] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[0] { 42 } = 0
// expected-error@-1 {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[] { 42 } = 0 // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
}
func keypath_to_subscript_to_property(_ lens: inout Lens<Array<Rectangle>>) {
_ = lens[0].topLeft.x
_ = lens[0].topLeft.y
_ = lens[0].topLeft.x = Lens(0)
_ = lens[0].topLeft.y = Lens(1)
// expected-error@-1 {{cannot assign to property: 'y' is a 'let' constant}}
}
@dynamicMemberLookup
struct SingleChoiceLens<T> {
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return obj[keyPath: member] }
set { obj[keyPath: member] = newValue }
}
}
// Make sure that disjunction filtering optimization doesn't
// impede keypath dynamic member lookup by eagerly trying to
// simplify disjunctions with a single viable choice.
func test_lens_with_a_single_choice(a: inout SingleChoiceLens<[Int]>) {
a[0] = 1 // Ok
}
func test_chain_of_recursive_lookups(_ lens: Lens<Lens<Lens<Point>>>) {
_ = lens.x
_ = lens.y
_ = lens.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
// Make sure that 'obj' field could be retrieved at any level
_ = lens.obj
_ = lens.obj.obj
_ = lens.obj.x
_ = lens.obj.obj.x
_ = \Lens<Lens<Point>>.x
_ = \Lens<Lens<Point>>.obj.x
}
// KeyPath Dynamic Member Lookup can't refer to methods, mutating setters and static members
// because of the KeyPath limitations
func invalid_refs_through_dynamic_lookup() {
struct S {
static var foo: Int = 42
func bar() -> Q { return Q() }
static func baz(_: String) -> Int { return 0 }
}
struct Q {
var faz: Int = 0
}
func test(_ lens: A<S>) {
_ = lens.foo // expected-error {{dynamic key path member lookup cannot refer to static member 'foo'}}
_ = lens.bar() // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}}
_ = lens.bar().faz + 1 // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}}
_ = lens.baz("hello") // expected-error {{dynamic key path member lookup cannot refer to static method 'baz'}}
}
}
| apache-2.0 | 3fc472a64be2c653d5ae940e2328166f | 27.046377 | 186 | 0.610996 | 3.884384 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Internals/Testing/AKTester.swift | 1 | 2370 | //
// AKTester.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Testing node
public class AKTester: AKNode, AKToggleable {
// MARK: - Properties
private var internalAU: AKTesterAudioUnit?
private var testedNode: AKToggleable?
private var token: AUParameterObserverToken?
var totalSamples = 0
/// Calculate the MD5
public var MD5: String {
return (self.internalAU?.getMD5())!
}
/// Flag on whether or not the test is still in progress
public var isStarted: Bool {
return Int((self.internalAU?.getSamples())!) < totalSamples
}
// MARK: - Initializers
/// Initialize this test node
///
/// - Parameters:
/// - input: AKNode to test
/// - sample: Number of sample to product
///
public init(_ input: AKNode, samples: Int) {
testedNode = input as? AKToggleable
totalSamples = samples
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = fourCC("tstr")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKTesterAudioUnit.self,
asComponentDescription: description,
name: "Local AKTester",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKTesterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
self.internalAU?.setSamples(Int32(samples))
}
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
testedNode?.start()
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | 1a38e3c45def08069c6bf64514ffa3ae | 27.902439 | 83 | 0.635865 | 5.140998 | false | true | false | false |
hgani/ganilib-ios | glib/Classes/View/GView.swift | 1 | 1912 | import UIKit
public protocol IView {
var size: CGSize { get }
func color(bg: UIColor) -> Self
func width(_ width: Int) -> Self
func width(_ width: LayoutSize) -> Self
func height(_ height: Int) -> Self
func height(_ height: LayoutSize) -> Self
func paddings(top: Float?, left: Float?, bottom: Float?, right: Float?) -> Self
}
open class GView: UIView {
private var helper: ViewHelper!
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
private func initialize() {
helper = ViewHelper(self)
}
// Needed for helper.width() and helper.height()
open override func didMoveToSuperview() {
super.didMoveToSuperview()
helper.didMoveToSuperview()
}
@discardableResult
public func width(_ width: Int) -> Self {
helper.width(width)
return self
}
@discardableResult
public func width(_ width: LayoutSize) -> Self {
helper.width(width)
return self
}
@discardableResult
public func width(weight: Float) -> Self {
helper.width(weight: weight)
return self
}
@discardableResult
public func height(_ height: Int) -> Self {
helper.height(height)
return self
}
@discardableResult
public func height(_ height: LayoutSize) -> Self {
helper.height(height)
return self
}
@discardableResult
public func color(bg: UIColor?) -> Self {
if let bgColor = bg {
backgroundColor = bgColor
}
return self
}
@discardableResult
public func border(color: UIColor?, width: Float = 1, corner: Float = 6) -> Self {
helper.border(color: color, width: width, corner: corner)
return self
}
}
| mit | 3f1528ed8d5fea66b4ee7f84cd9545d3 | 22.036145 | 86 | 0.597803 | 4.509434 | false | false | false | false |
jpipard/DKImagePickerController | DKImagePickerControllerDemo/ViewController.swift | 1 | 6041 | //
// ViewController.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 14-10-1.
// Copyright (c) 2014年 ZhangAo. All rights reserved.
//
import UIKit
import Photos
import AVKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet var previewView: UICollectionView?
var assets: [DKAsset]?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showImagePickerWithAssetType(assetType: DKImagePickerControllerAssetType,
allowMultipleType: Bool,
sourceType: DKImagePickerControllerSourceType = .Both,
allowsLandscape: Bool,
singleSelect: Bool) {
let pickerController = DKImagePickerController()
// Custom camera
// pickerController.UIDelegate = CustomUIDelegate()
// pickerController.modalPresentationStyle = .OverCurrentContext
pickerController.assetType = assetType
pickerController.allowsLandscape = allowsLandscape
pickerController.allowMultipleTypes = allowMultipleType
pickerController.sourceType = sourceType
pickerController.singleSelect = singleSelect
pickerController.numberColor = UIColor.yellowColor()
pickerController.checkedBackgroundImgColor = UIColor.orangeColor()
pickerController.backgroundCollectionViewColor = UIColor.blackColor()
// pickerController.showsCancelButton = true
// pickerController.showsEmptyAlbums = false
// pickerController.defaultAssetGroup = PHAssetCollectionSubtype.SmartAlbumFavorites
// Clear all the selected assets if you used the picker controller as a single instance.
// pickerController.defaultSelectedAssets = nil
pickerController.defaultSelectedAssets = self.assets
pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in
print("didSelectAssets")
self.assets = assets
self.previewView?.reloadData()
}
if UI_USER_INTERFACE_IDIOM() == .Pad {
pickerController.modalPresentationStyle = .FormSheet
}
self.presentViewController(pickerController, animated: true) {}
}
func playVideo(asset: AVAsset) {
let avPlayerItem = AVPlayerItem(asset: asset)
let avPlayer = AVPlayer(playerItem: avPlayerItem)
let player = AVPlayerViewController()
player.player = avPlayer
avPlayer.play()
self.presentViewController(player, animated: true, completion: nil)
}
// MARK: - UITableViewDataSource, UITableViewDelegate methods
struct Demo {
static let titles = [
["Pick All", "Pick photos only", "Pick videos only", "Pick All (only photos or videos)"],
["Take a picture"],
["Hides camera"],
["Allows landscape"],
["Single select"]
]
static let types: [DKImagePickerControllerAssetType] = [.AllAssets, .AllPhotos, .AllVideos, .AllAssets]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return Demo.titles.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Demo.titles[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = Demo.titles[indexPath.section][indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let assetType = Demo.types[indexPath.row]
let allowMultipleType = !(indexPath.row == 0 && indexPath.section == 3)
let sourceType: DKImagePickerControllerSourceType = indexPath.section == 1 ? .Camera :
(indexPath.section == 2 ? .Photo : .Both)
let allowsLandscape = indexPath.section == 3
let singleSelect = indexPath.section == 4
showImagePickerWithAssetType(
assetType,
allowMultipleType: allowMultipleType,
sourceType: sourceType,
allowsLandscape: allowsLandscape,
singleSelect: singleSelect
)
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.assets?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let asset = self.assets![indexPath.row]
var cell: UICollectionViewCell?
var imageView: UIImageView?
if asset.isVideo {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellVideo", forIndexPath: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellImage", forIndexPath: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
}
if let cell = cell, imageView = imageView {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let tag = indexPath.row + 1
cell.tag = tag
asset.fetchImageWithSize(layout.itemSize.toPixel(), completeBlock: { image, info in
if cell.tag == tag {
imageView.image = image
}
})
}
return cell!
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let asset = self.assets![indexPath.row]
asset.fetchAVAssetWithCompleteBlock { (avAsset, info) in
dispatch_async(dispatch_get_main_queue(), { () in
self.playVideo(avAsset!)
})
}
}
}
| mit | 6d213b9b59d4e1d274bd293f50d79889 | 33.907514 | 138 | 0.69995 | 5.260453 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Settings/Privacy/AppLockViewController.swift | 1 | 22098 | //
// AppLockViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 06/03/2022.
// Copyright © 2022 Piwigo.org. All rights reserved.
//
import Foundation
import piwigoKit
import UIKit
enum AppLockAction {
case enterPasscode
case verifyPasscode
case modifyPasscode
case unlockApp
}
protocol AppLockDelegate: NSObjectProtocol {
func loginOrReloginAndResumeUploads()
}
class AppLockViewController: UIViewController {
weak var delegate: AppLockDelegate?
@IBOutlet weak var blurEffectView: UIVisualEffectView!
@IBOutlet weak var vibrancyEffectView: UIVisualEffectView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var titleLabelHorOffset: NSLayoutConstraint!
@IBOutlet weak var titleLabelVertOffset: NSLayoutConstraint!
@IBOutlet weak var digitStack: UIStackView!
@IBOutlet weak var digit1: UIButton!
@IBOutlet weak var digit2: UIButton!
@IBOutlet weak var digit3: UIButton!
@IBOutlet weak var digit4: UIButton!
@IBOutlet weak var digit5: UIButton!
@IBOutlet weak var digit6: UIButton!
@IBOutlet weak var mainStack: UIStackView!
@IBOutlet weak var mainStackHorOffset: NSLayoutConstraint!
@IBOutlet weak var mainStackVertOffset: NSLayoutConstraint!
@IBOutlet weak var stackRow1: UIStackView!
@IBOutlet weak var stackRow2: UIStackView!
@IBOutlet weak var stackRow3: UIStackView!
@IBOutlet weak var stackRow4: UIStackView!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
@IBOutlet weak var button5: UIButton!
@IBOutlet weak var button6: UIButton!
@IBOutlet weak var button7: UIButton!
@IBOutlet weak var button8: UIButton!
@IBOutlet weak var button9: UIButton!
@IBOutlet weak var button0: UIButton!
@IBOutlet weak var button0width: NSLayoutConstraint!
@IBOutlet weak var buttonBackSpace: UIButton!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var infoLabelMaxWidth: NSLayoutConstraint!
@IBOutlet weak var infoLabelVertOffset: NSLayoutConstraint!
private var passcode = String()
private var passcodeToVerify = String()
private var wantedAction = AppLockAction.enterPasscode
func config(password: String = "", forAction action:AppLockAction) {
wantedAction = action
switch action {
case .enterPasscode, .modifyPasscode:
passcode = ""
case .verifyPasscode:
passcodeToVerify = password
case .unlockApp:
passcodeToVerify = AppVars.shared.appLockKey.decrypted()
}
}
private var _diameter: CGFloat = 60.0
var diameter: CGFloat {
get {
return _diameter
}
set(value){
_diameter = value
// Stack spaces
let spacing = value / 5
mainStack.spacing = spacing
stackRow1.spacing = spacing
stackRow2.spacing = spacing
stackRow3.spacing = spacing
stackRow4.spacing = spacing
// Buttons
let radius = value / 2
button0.layer.cornerRadius = radius
button1.layer.cornerRadius = radius
button2.layer.cornerRadius = radius
button3.layer.cornerRadius = radius
button4.layer.cornerRadius = radius
button5.layer.cornerRadius = radius
button6.layer.cornerRadius = radius
button7.layer.cornerRadius = radius
button8.layer.cornerRadius = radius
button9.layer.cornerRadius = radius
buttonBackSpace.layer.cornerRadius = radius
// Set buttons size and distribution
button0width.constant = diameter
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("settingsHeader_privacy", comment: "Privacy")
}
@objc func applyColorPalette() {
// Navigation bar (if any)
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes as [NSAttributedString.Key : Any]
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Initialise colours
var labelsColor = UIColor.piwigoColorText()
var digitBorderColor = UIColor.clear.cgColor
var buttonTitleColor = UIColor.piwigoColorRightLabel()
var buttonBckgColor = UIColor.piwigoColorCellBackground()
var buttonBorderColor = UIColor.clear.cgColor
if wantedAction == .unlockApp {
if UIAccessibility.isReduceTransparencyEnabled {
// Settings ▸ Accessibility ▸ Display & Text Size ▸ Reduce Transparency is enabled
/// —> No blur effect, fixed colour background
view.backgroundColor = UIColor.piwigoColorBrown()
blurEffectView.effect = .none
vibrancyEffectView.effect = .none
labelsColor = .white
buttonBckgColor = .clear
buttonTitleColor = .init(white: 0.8, alpha: 1.0)
buttonBorderColor = buttonTitleColor.cgColor
}
else {
// Settings ▸ Accessibility ▸ Display & Text Size ▸ Reduce Transparency is disabled
/// —> Blur and vibrancy effects
view.backgroundColor = .clear
var blurEffect = UIBlurEffect(style: .dark)
if AppVars.shared.isDarkPaletteActive {
blurEffect = UIBlurEffect(style: .light)
}
blurEffectView.effect = blurEffect
vibrancyEffectView.effect = UIVibrancyEffect(blurEffect: blurEffect)
labelsColor = .white
buttonBckgColor = .clear
buttonTitleColor = UIColor.piwigoColorNumkey()
buttonBorderColor = buttonTitleColor.cgColor
digitBorderColor = buttonTitleColor.cgColor
}
} else { // Enter or Verify passcode
view.backgroundColor = .piwigoColorBackground()
blurEffectView.effect = .none
vibrancyEffectView.effect = .none
}
// Background, title and info
titleLabel.textColor = labelsColor
titleLabel.tintColor = labelsColor
infoLabel.textColor = labelsColor
infoLabel.tintColor = labelsColor
// App Lock digits
digit1.layer.borderColor = digitBorderColor
digit2.layer.borderColor = digitBorderColor
digit3.layer.borderColor = digitBorderColor
digit4.layer.borderColor = digitBorderColor
digit5.layer.borderColor = digitBorderColor
digit6.layer.borderColor = digitBorderColor
updateDigits()
button0.layer.borderColor = buttonBorderColor
button0.backgroundColor = buttonBckgColor
button0.setTitleColor(buttonTitleColor, for: .normal)
button1.layer.borderColor = buttonBorderColor
button1.setTitleColor(buttonTitleColor, for: .normal)
button1.backgroundColor = buttonBckgColor
button2.layer.borderColor = buttonBorderColor
button2.backgroundColor = buttonBckgColor
button2.setTitleColor(buttonTitleColor, for: .normal)
button3.layer.borderColor = buttonBorderColor
button3.backgroundColor = buttonBckgColor
button3.setTitleColor(buttonTitleColor, for: .normal)
button4.layer.borderColor = buttonBorderColor
button4.backgroundColor = buttonBckgColor
button4.setTitleColor(buttonTitleColor, for: .normal)
button5.layer.borderColor = buttonBorderColor
button5.backgroundColor = buttonBckgColor
button5.setTitleColor(buttonTitleColor, for: .normal)
button6.layer.borderColor = buttonBorderColor
button6.backgroundColor = buttonBckgColor
button6.setTitleColor(buttonTitleColor, for: .normal)
button7.layer.borderColor = buttonBorderColor
button7.backgroundColor = buttonBckgColor
button7.setTitleColor(buttonTitleColor, for: .normal)
button8.layer.borderColor = buttonBorderColor
button8.backgroundColor = buttonBckgColor
button8.setTitleColor(buttonTitleColor, for: .normal)
button9.layer.borderColor = buttonBorderColor
button9.backgroundColor = buttonBckgColor
button9.setTitleColor(buttonTitleColor, for: .normal)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Title and Info labels
switch wantedAction {
case .enterPasscode, .unlockApp:
titleLabel.text = NSLocalizedString("settings_appLockEnter", comment: "Enter Passcode")
case .verifyPasscode:
titleLabel.text = NSLocalizedString("settings_appLockVerify", comment: "Verify Passcode")
case .modifyPasscode:
titleLabel.text = NSLocalizedString("settings_appLockModify", comment: "Modify Passcode")
}
infoLabel.text = NSLocalizedString("settings_appLockInfo", comment: "With App Lock, ...")
// Set constraints, colors, fonts, etc.
configConstraints()
applyColorPalette()
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Update the constraints on orientation change
coordinator.animate(alongsideTransition: { _ in
self.configConstraints()
})
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
private func configConstraints() {
// Get the safe area width and height
var vertOffset = CGFloat.zero // Used when safe area unknown i.e. before iOS 11
var safeAreaWidth = view.bounds.size.width
var safeAreaHeight = view.bounds.size.height
if #available(iOS 11.0, *) {
safeAreaWidth -= view.safeAreaInsets.left + view.safeAreaInsets.right
safeAreaHeight -= view.safeAreaInsets.top + view.safeAreaInsets.bottom
} else {
vertOffset += UIApplication.shared.statusBarFrame.size.height
safeAreaHeight -= vertOffset
}
if let nav = navigationController {
// Remove the height of the navigation bar
vertOffset += nav.navigationBar.bounds.height
safeAreaHeight -= nav.navigationBar.bounds.height
}
// Get device orientation
var orientation = UIInterfaceOrientation.portrait
if #available(iOS 13.0, *) {
orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? .portrait
} else {
orientation = UIApplication.shared.statusBarOrientation
}
// Initialise constants
let margin: CGFloat = 16
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let attributes = [NSAttributedString.Key.font: infoLabel.font!]
// Constraints depend on orientation
if orientation.isPortrait || UIDevice.current.userInterfaceIdiom == .pad {
// iPhone in portrait mode ▸ All centered horizontally
titleLabelHorOffset.constant = CGFloat.zero
mainStackHorOffset.constant = CGFloat.zero
// Calculate the required height of the App Lock info
/// The minimum width of a screen is of 320 points.
/// See https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/
let maxWidth: CGFloat = min(safeAreaWidth, 320) - 2*margin
let widthConstraint: CGSize = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)
let height = infoLabel.text?.boundingRect(with: widthConstraint, options: .usesLineFragmentOrigin,
attributes: attributes, context: context).height ?? CGFloat(60)
// Calculate diameter of buttons and update UI elements
/// See AppLockViewController.nb file
let dWidth: CGFloat = floor(5 * (safeAreaWidth - 2*margin)/17)
let dHeight: CGFloat = floor(5 * (safeAreaHeight - 23.5 - 16 - 10 - height - 4*margin)/23)
diameter = min(min(dWidth, dHeight), 80)
// Set vertical constraints
let mainStackHeight: CGFloat = 23*diameter/5
safeAreaHeight -= mainStackHeight
let topElementsHeight: CGFloat = 23.5 + 16 + 10
if #available(iOS 11.0, *) {
// Safe area known
titleLabelVertOffset.constant = (safeAreaHeight/2 - topElementsHeight)/2
mainStackVertOffset.constant = CGFloat.zero
} else {
// Safe area unknown
titleLabelVertOffset.constant = (safeAreaHeight/2 - topElementsHeight)/2 + vertOffset
mainStackVertOffset.constant = vertOffset / 2
}
infoLabelMaxWidth.constant = maxWidth
infoLabelVertOffset.constant = (safeAreaHeight/2 - height) / 2
}
else {
// iPhone in landscape mode ▸ Labels and numpad side by side
if #available(iOS 11.0, *) {
mainStackVertOffset.constant = CGFloat.zero
} else {
mainStackVertOffset.constant = vertOffset / 2
}
let horOffset = min(safeAreaWidth/4.0, 300.0)
if orientation == .landscapeLeft {
titleLabelHorOffset.constant = horOffset
mainStackHorOffset.constant = horOffset
} else {
titleLabelHorOffset.constant = -horOffset
mainStackHorOffset.constant = -horOffset
}
// Calculate diameter of buttons and update UI elements
/// See AppLockViewController.nb file
let dWidth: CGFloat = 5 * (safeAreaWidth - 4*margin)/34
let dHeight: CGFloat = 5 * (safeAreaHeight - 2*margin)/23
diameter = min(min(dWidth, dHeight), 80)
// Fix size and vertical positions of labels
titleLabelVertOffset.constant = safeAreaHeight/2 - CGFloat(100)
let maxWidth: CGFloat = min(safeAreaWidth/2, 320) - 2*margin
infoLabelMaxWidth.constant = maxWidth
infoLabelVertOffset.constant = safeAreaHeight/2 - CGFloat(100)
}
}
// MARK: - Numpad management
@IBAction func touchDown(_ sender: UIButton) {
// Apply darker backgroud colour while pressing key (reveals the glowing number).
if wantedAction != .unlockApp {
sender.backgroundColor = UIColor.piwigoColorRightLabel()
}
}
@IBAction func touchUpInside(_ sender: UIButton) {
// Re-apply normal background colour when the key is released
if wantedAction != .unlockApp {
sender.backgroundColor = UIColor.piwigoColorCellBackground()
}
// No more than 6 digits
if passcode.count == 6 { return }
// Retrieve pressed key
guard let buttonTitle = sender.currentTitle else { return }
if "0123456789".contains(buttonTitle) == false { return }
// Add typed digit to passcode
passcode.append(buttonTitle)
// Update digits
updateDigits()
// Passcode complete?
if passcode.count < 6 { return }
// Manage provided passcode
switch wantedAction {
case .enterPasscode, .modifyPasscode: // Just finshed entering passcode —> verify passcode
let appLockSB = UIStoryboard(name: "AppLockViewController", bundle: nil)
guard let appLockVC = appLockSB.instantiateViewController(withIdentifier: "AppLockViewController") as? AppLockViewController else { return }
appLockVC.config(password: passcode, forAction: .verifyPasscode)
navigationController?.pushViewController(appLockVC, animated: true)
case .verifyPasscode: // Passcode re-entered
// Do passcodes match?
if passcode != passcodeToVerify {
// Passcode not verified!
shakeDigitRow()
return
}
// Activate App-Lock if this is the first time we create a passcode
if AppVars.shared.appLockKey.isEmpty {
AppVars.shared.isAppLockActive = true
}
// Store encrypted passcode
AppVars.shared.appLockKey = passcode.encrypted()
// Return to the Settings view
if let vc = navigationController?.children.filter({ $0 is LockOptionsViewController}).first {
navigationController?.popToViewController(vc, animated: true)
} else {
// Return to the root album
self.dismiss(animated: true)
}
case .unlockApp:
// Do passcodes match?
if passcode != passcodeToVerify {
// Incorrect passcode!
shakeDigitRow()
return
}
// User allowed to access app
AppVars.shared.isAppUnlocked = true
// Unlock the app
dismiss(animated: true) {
// Re-enable biometry for the next time
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.didCancelBiometricsAuthentication = false
// Login/relogin and resume uploads
self.delegate?.loginOrReloginAndResumeUploads()
}
}
}
@IBAction func touchedBackSpace(_ sender: Any) {
// NOP if no digit
if passcode.isEmpty { return }
// Remove last digit
passcode.removeLast()
// Update digits
updateDigits()
}
private func updateDigits() {
let nberOfDigits = passcode.count
// Digit background colour
var digitKnownColor = UIColor.piwigoColorOrange()
var digitUnknowColor = UIColor.piwigoColorCellBackground()
if wantedAction == .unlockApp {
if UIAccessibility.isReduceTransparencyEnabled {
// Settings ▸ Accessibility ▸ Display & Text Size ▸ Reduce Transparency is enabled
digitUnknowColor = .init(white: 0.8, alpha: 1.0)
} else {
// Settings ▸ Accessibility ▸ Display & Text Size ▸ Reduce Transparency is disabled
digitKnownColor = UIColor.piwigoColorNumkey()
digitUnknowColor = .clear
}
}
digit1.backgroundColor = nberOfDigits > 0 ? digitKnownColor : digitUnknowColor
digit2.backgroundColor = nberOfDigits > 1 ? digitKnownColor : digitUnknowColor
digit3.backgroundColor = nberOfDigits > 2 ? digitKnownColor : digitUnknowColor
digit4.backgroundColor = nberOfDigits > 3 ? digitKnownColor : digitUnknowColor
digit5.backgroundColor = nberOfDigits > 4 ? digitKnownColor : digitUnknowColor
digit6.backgroundColor = nberOfDigits > 5 ? digitKnownColor : digitUnknowColor
// Back space title colour
if nberOfDigits == 0 {
buttonBackSpace.setTitleColor(.clear, for: .normal)
} else {
var digitTitleColor = UIColor.piwigoColorRightLabel()
if wantedAction == .unlockApp, !UIAccessibility.isReduceTransparencyEnabled {
// Settings ▸ Accessibility ▸ Display & Text Size ▸ Reduce Transparency is disabled
digitTitleColor = UIColor.piwigoColorNumkey()
}
buttonBackSpace.setTitleColor(digitTitleColor, for: .normal)
}
}
private func shakeDigitRow() {
// Move digits to the left and right several times
self.digitStack.shakeHorizontally {
// Re-verify passcode
self.passcode = ""
UIView.animate(withDuration: 1) {
self.updateDigits()
}
}
// If the device supports Core Haptics, exploit them.
if #available(iOS 13.0, *) {
HapticUtilities.shared.playHapticsFile(named: "VerificationFailed")
}
}
}
| mit | 499251918d8ca8222cf6a1290be54793 | 41.091603 | 152 | 0.632164 | 5.690402 | false | false | false | false |
jpipard/DKImagePickerController | DKImagePickerController/DKImagePickerControllerDefaultCamera.swift | 1 | 4513 | //
// DKImagePickerControllerDefaultCamera.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 16/3/7.
// Copyright © 2016年 ZhangAo. All rights reserved.
//
import UIKit
@objc
public class DKImagePickerControllerDefaultUIDelegate: NSObject, DKImagePickerControllerUIDelegate {
public weak var imagePickerController: DKImagePickerController!
public lazy var doneButton: UIButton = {
return self.createDoneButton()
}()
public func createDoneButton() -> UIButton {
let button = UIButton(type: UIButtonType.Custom)
button.setTitleColor(UINavigationBar.appearance().tintColor ?? self.imagePickerController.navigationBar.tintColor, forState: UIControlState.Normal)
button.addTarget(self.imagePickerController, action: #selector(DKImagePickerController.done), forControlEvents: UIControlEvents.TouchUpInside)
self.updateDoneButtonTitle(button)
return button
}
// Delegate methods...
public func prepareLayout(imagePickerController: DKImagePickerController, vc: UIViewController) {
if !imagePickerController.singleSelect {
vc.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.doneButton)
}
self.imagePickerController = imagePickerController
}
public func imagePickerControllerCreateCamera(imagePickerController: DKImagePickerController,
didCancel: (() -> Void),
didFinishCapturingImage: ((image: UIImage) -> Void),
didFinishCapturingVideo: ((videoURL: NSURL) -> Void)) -> UIViewController {
let camera = DKCamera()
camera.didCancel = { () -> Void in
didCancel()
}
camera.didFinishCapturingImage = { (image) in
didFinishCapturingImage(image: image)
}
self.checkCameraPermission(camera)
return camera
}
public func layoutForImagePickerController(imagePickerController: DKImagePickerController) -> UICollectionViewLayout.Type {
return DKAssetGroupGridLayout.self
}
public func imagePickerControllerCameraImage() -> UIImage {
return DKImageResource.cameraImage()
}
public func imagePickerController(imagePickerController: DKImagePickerController,
showsCancelButtonForVC vc: UIViewController) {
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel,
target: imagePickerController,
action: #selector(DKImagePickerController.dismiss))
}
public func imagePickerController(imagePickerController: DKImagePickerController,
hidesCancelButtonForVC vc: UIViewController) {
vc.navigationItem.leftBarButtonItem = nil
}
public func imagePickerController(imagePickerController: DKImagePickerController, didSelectAsset: DKAsset) {
self.updateDoneButtonTitle(self.doneButton)
}
public func imagePickerController(imagePickerController: DKImagePickerController, didDeselectAsset: DKAsset) {
self.updateDoneButtonTitle(self.doneButton)
}
public func imagePickerControllerDidReachMaxLimit(imagePickerController: DKImagePickerController) {
UIAlertView(title: DKImageLocalizedStringWithKey("maxLimitReached"),
message: String(format: DKImageLocalizedStringWithKey("maxLimitReachedMessage"), imagePickerController.maxSelectableCount),
delegate: nil,
cancelButtonTitle: DKImageLocalizedStringWithKey("ok"))
.show()
}
public func imagePickerControllerFooterView(imagePickerController: DKImagePickerController) -> UIView? {
return nil
}
// Internal
public func checkCameraPermission(camera: DKCamera) {
func cameraDenied() {
dispatch_async(dispatch_get_main_queue()) {
let permissionView = DKPermissionView.permissionView(.Camera)
camera.cameraOverlayView = permissionView
}
}
func setup() {
camera.cameraOverlayView = nil
}
DKCamera.checkCameraPermission { granted in
granted ? setup() : cameraDenied()
}
}
public func updateDoneButtonTitle(button: UIButton) {
if self.imagePickerController.selectedAssets.count > 0 {
button.setTitle(String(format: DKImageLocalizedStringWithKey("select"), self.imagePickerController.selectedAssets.count), forState: UIControlState.Normal)
} else {
button.setTitle(DKImageLocalizedStringWithKey("done"), forState: UIControlState.Normal)
}
button.sizeToFit()
}
}
| mit | e84843fa839e814a0a7b867c542ce9f2 | 34.511811 | 157 | 0.723282 | 5.420673 | false | false | false | false |
mlmc03/SwiftFM-DroidFM | SwiftFM/SwiftyJSON.swift | 1 | 36628 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
public let ErrorInvalidJSON: Int! = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error.memory = aError
}
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: AnyObject]()
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
private var rawArray: [AnyObject] = []
private var rawDictionary: [String : AnyObject] = [:]
private var rawString: String = ""
private var rawNumber: NSNumber = 0
private var rawNull: NSNull = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError? = nil
/// Object in JSON
public var object: AnyObject {
get {
switch self.type {
case .Array:
return self.rawArray
case .Dictionary:
return self.rawDictionary
case .String:
return self.rawString
case .Number:
return self.rawNumber
case .Bool:
return self.rawNumber
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
self.rawNumber = number
case let string as String:
_type = .String
self.rawString = string
case _ as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
self.rawArray = array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
self.rawDictionary = dictionary
default:
_type = .Unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
@available(*, unavailable, renamed="null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
// MARK: - CollectionType, SequenceType, Indexable
extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
public typealias Generator = JSONGenerator
public typealias Index = JSONIndex
public var startIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.startIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
default:
return JSONIndex()
}
}
public var endIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.endIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
default:
return JSONIndex()
}
}
public subscript (position: JSON.Index) -> JSON.Generator.Element {
switch self.type {
case .Array:
return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
case .Dictionary:
let (key, value) = self.rawDictionary[position.dictionaryIndex!]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `true`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return self.rawArray.isEmpty
case .Dictionary:
return self.rawDictionary.isEmpty
default:
return true
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
switch self.type {
case .Array:
return self.rawArray.count
case .Dictionary:
return self.rawDictionary.count
default:
return 0
}
}
public func underestimateCount() -> Int {
switch self.type {
case .Array:
return self.rawArray.underestimateCount()
case .Dictionary:
return self.rawDictionary.underestimateCount()
default:
return 0
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of JSON.
*/
public func generate() -> JSON.Generator {
return JSON.Generator(self)
}
}
public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
let arrayIndex: Int?
let dictionaryIndex: DictionaryIndex<String, AnyObject>?
let type: Type
init(){
self.arrayIndex = nil
self.dictionaryIndex = nil
self.type = .Unknown
}
init(arrayIndex: Int) {
self.arrayIndex = arrayIndex
self.dictionaryIndex = nil
self.type = .Array
}
init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
self.arrayIndex = nil
self.dictionaryIndex = dictionaryIndex
self.type = .Dictionary
}
public func successor() -> JSONIndex {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.arrayIndex!.successor())
case .Dictionary:
return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
default:
return JSONIndex()
}
}
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex == rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex == rhs.dictionaryIndex
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex < rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex < rhs.dictionaryIndex
default:
return false
}
}
public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex <= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex <= rhs.dictionaryIndex
default:
return false
}
}
public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex >= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex >= rhs.dictionaryIndex
default:
return false
}
}
public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex > rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex > rhs.dictionaryIndex
default:
return false
}
}
public struct JSONGenerator : GeneratorType {
public typealias Element = (String, JSON)
private let type: Type
private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
private var arrayGenerate: IndexingGenerator<[AnyObject]>?
private var arrayIndex: Int = 0
init(_ json: JSON) {
self.type = json.type
if type == .Array {
self.arrayGenerate = json.rawArray.generate()
}else {
self.dictionayGenerate = json.rawDictionary.generate()
}
}
public mutating func next() -> JSONGenerator.Element? {
switch self.type {
case .Array:
if let o = self.arrayGenerate!.next() {
return (String(self.arrayIndex++), JSON(o))
} else {
return nil
}
case .Dictionary:
if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() {
return (k, JSON(v))
} else {
return nil
}
default:
return nil
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol JSONSubscriptType {}
extension Int: JSONSubscriptType {}
extension String: JSONSubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .Array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .Dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .Dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: JSONSubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.removeAtIndex(0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
var d = dictionary
d[element.0] = element.1
return d
})
}
}
extension JSON: Swift.ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: Swift.NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
guard NSJSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) as? String
} catch _ {
return nil
}
case .String:
return self.rawString
case .Number:
return self.rawNumber.stringValue
case .Bool:
return self.rawNumber.boolValue.description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.Printable, Swift.DebugPrintable {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .Dictionary {
return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
var d = dictionary
d[element.0] = JSON(element.1)
return d
}
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: Swift.BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.rawNumber.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
// public var string: String {
// get {
// switch self.type {
// case .String:
// return self.object as! String
// case .Number:
// return self.object.stringValue
// case .Bool:
// return (self.object as! Bool).description
// default:
// return ""
// }
// }
// set {
// self.object = NSString(string:newValue)
// }
// }
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.rawNumber
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber() { // indicates parse error
return NSDecimalNumber.zero()
}
return decimal
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func isExists() -> Bool{
if let errorValue = error where errorValue.code == ErrorNotExist{
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber == rhs.rawNumber
case (.String, .String):
return lhs.rawString == rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber <= rhs.rawNumber
case (.String, .String):
return lhs.rawString <= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber >= rhs.rawNumber
case (.String, .String):
return lhs.rawString >= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber > rhs.rawNumber
case (.String, .String):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber < rhs.rawNumber
case (.String, .String):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
|| (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
} | apache-2.0 | 842fd8e77cd6e041dfaaf344fa2cf180 | 26.112509 | 265 | 0.535519 | 4.816305 | false | false | false | false |
crass45/PoGoApiAppleWatchExample | PoGoApiAppleWatchExample/PGoApi/MapViewController.swift | 1 | 3933 | //
// MapViewController.swift
// PGoApi
//
// Created by Jose Luis on 16/8/16.
// Copyright © 2016 crass45. All rights reserved.
//
import UIKit
import MapKit
import PGoApi
class MapViewController: UIViewController, MKMapViewDelegate {
var usuAnotation = TrainerAnnotation()
@IBOutlet weak var mapa: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapa.delegate = self
// Do any additional setup after loading the view.
let span = MKCoordinateSpan(latitudeDelta: Double(0.1), longitudeDelta: Double(0.1))
let region = MKCoordinateRegion(center: userLocation, span: span)
mapa.setRegion(region, animated: true)
drawAnnotation()
mapa.mapType = MKMapType.SatelliteFlyover
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MapViewController.drawAnnotation), name: NEW_POKEMONS_NOTIFICATION, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MapViewController.drawTrainer), name: UPDATE_LOCATION_NOTIFICATION, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NEW_POKEMONS_NOTIFICATION, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UPDATE_LOCATION_NOTIFICATION, object: nil)
}
func drawTrainer(){
mapa.removeAnnotation(usuAnotation)
usuAnotation = TrainerAnnotation()
mapa.addAnnotation(usuAnotation)
}
func drawAnnotation(){
mapa.removeAnnotations(mapa.annotations)
drawTrainer()
mapa.addAnnotation(usuAnotation)
for poke in catchablePokes {
let annotation = PokemonAnnotation(poke: poke)
mapa.addAnnotation(annotation)
}
for fort in gimnasios {
let annotation = FortAnnotation(poke: fort)
mapa.addAnnotation(annotation)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let reuseID = "pin"
let aview = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
if let trainer = annotation as? TrainerAnnotation {
aview.pinColor = MKPinAnnotationColor.Red
aview.canShowCallout = true
}
if let poke = annotation as? PokemonAnnotation{
let pokemonView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pokemon")
pokemonView.image = UIImage(named: poke.imagenString)
pokemonView.canShowCallout = true
return pokemonView
// aview.pinColor = MKPinAnnotationColor.Green
// aview.canShowCallout = true
}
if let poke = annotation as? FortAnnotation{
aview.pinColor = MKPinAnnotationColor.Purple
aview.canShowCallout = true
}
if let poke = annotation as? SpawnPointAnnotation{
aview.pinColor = MKPinAnnotationColor.Red
aview.canShowCallout = true
}
return aview
}
}
| mit | 4fa643e752f93fceb20f6ee09028cae2 | 31.229508 | 163 | 0.639624 | 5.453537 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Extensions/Array+HeroModifier.swift | 9 | 1924 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 UIKit
internal extension Array {
func get(_ index: Int) -> Element? {
if index < count {
return self[index]
}
return nil
}
}
internal extension Array where Element: ExprNode {
func getCGFloat(_ index: Int) -> CGFloat? {
if let s = get(index) as? NumberNode {
return CGFloat(s.value)
}
return nil
}
func getDouble(_ index: Int) -> Double? {
if let s = get(index) as? NumberNode {
return Double(s.value)
}
return nil
}
func getFloat(_ index: Int) -> Float? {
if let s = get(index) as? NumberNode {
return s.value
}
return nil
}
func getBool(_ index: Int) -> Bool? {
if let s = get(index) as? VariableNode, let f = Bool(s.name) {
return f
}
return nil
}
}
| mit | e0e59e1b333b63ef578457e46edd3bb7 | 31.610169 | 80 | 0.68763 | 4.025105 | false | false | false | false |
shaps80/Stack | Example/Stack/DataViewController.swift | 1 | 4617 | /*
Copyright © 2015 Shaps Mohsenin. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY SHAPS MOHSENIN `AS IS' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE APP BUSINESS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import CoreData
class DataViewController: UITableViewController, NSFetchedResultsControllerDelegate {
/*
-------------------------------------------------------------------------
This class is purely NSFetchedResultsController boilerplate code!
Please checkout StackViewController for example code.
-------------------------------------------------------------------------
*/
// MARK: Subclassers Methods
@IBAction func add(sender: AnyObject?) { /* implement in subclass */ }
func delete(atIndexPath indexPath: NSIndexPath) { /* implement in subclass */ }
// MARK: TableView DataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.fetchedObjects?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
if let person = fetchedResultsController.objectAtIndexPath(indexPath) as? Person {
cell.textLabel?.text = person.name ?? "Unknown"
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
delete(atIndexPath: indexPath)
}
}
// MARK: FetchedResultsController Delegate
var fetchedResultsController: NSFetchedResultsController!
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
if !NSThread.isMainThread() {
fatalError("Fetched Results Controller executed off the main thread!!")
}
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
default:
break
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
print("FRC: Inserted -- \(anObject)")
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
print("FRC: Deleted -- \(anObject)")
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
}
| mit | cba86c7655f47f8a500371675f8ee98f | 36.836066 | 209 | 0.728986 | 5.895275 | false | false | false | false |
jwalsh/mal | swift3/Sources/step6_file/main.swift | 3 | 4867 | import Foundation
// read
func READ(str: String) throws -> MalVal {
return try read_str(str)
}
// eval
func eval_ast(ast: MalVal, _ env: Env) throws -> MalVal {
switch ast {
case MalVal.MalSymbol:
return try env.get(ast)
case MalVal.MalList(let lst, _):
return list(try lst.map { try EVAL($0, env) })
case MalVal.MalVector(let lst, _):
return vector(try lst.map { try EVAL($0, env) })
case MalVal.MalHashMap(let dict, _):
var new_dict = Dictionary<String,MalVal>()
for (k,v) in dict { new_dict[k] = try EVAL(v, env) }
return hash_map(new_dict)
default:
return ast
}
}
func EVAL(orig_ast: MalVal, _ orig_env: Env) throws -> MalVal {
var ast = orig_ast, env = orig_env
while true {
switch ast {
case MalVal.MalList(let lst, _): if lst.count == 0 { return ast }
default: return try eval_ast(ast, env)
}
switch ast {
case MalVal.MalList(let lst, _):
switch lst[0] {
case MalVal.MalSymbol("def!"):
return try env.set(lst[1], try EVAL(lst[2], env))
case MalVal.MalSymbol("let*"):
let let_env = try Env(env)
var binds = Array<MalVal>()
switch lst[1] {
case MalVal.MalList(let l, _): binds = l
case MalVal.MalVector(let l, _): binds = l
default:
throw MalError.General(msg: "Invalid let* bindings")
}
var idx = binds.startIndex
while idx < binds.endIndex {
let v = try EVAL(binds[idx.successor()], let_env)
try let_env.set(binds[idx], v)
idx = idx.successor().successor()
}
env = let_env
ast = lst[2] // TCO
case MalVal.MalSymbol("do"):
let slc = lst[1..<lst.endIndex.predecessor()]
try eval_ast(list(Array(slc)), env)
ast = lst[lst.endIndex.predecessor()] // TCO
case MalVal.MalSymbol("if"):
switch try EVAL(lst[1], env) {
case MalVal.MalFalse, MalVal.MalNil:
if lst.count > 3 {
ast = lst[3] // TCO
} else {
return MalVal.MalNil
}
default:
ast = lst[2] // TCO
}
case MalVal.MalSymbol("fn*"):
return malfunc( {
return try EVAL(lst[2], Env(env, binds: lst[1],
exprs: list($0)))
}, ast:[lst[2]], env:env, params:[lst[1]])
default:
switch try eval_ast(ast, env) {
case MalVal.MalList(let elst, _):
switch elst[0] {
case MalVal.MalFunc(let fn, nil, _, _, _, _):
let args = Array(elst[1..<elst.count])
return try fn(args)
case MalVal.MalFunc(_, let a, let e, let p, _, _):
let args = Array(elst[1..<elst.count])
env = try Env(e, binds: p![0],
exprs: list(args)) // TCO
ast = a![0] // TCO
default:
throw MalError.General(msg: "Cannot apply on '\(elst[0])'")
}
default: throw MalError.General(msg: "Invalid apply")
}
}
default:
throw MalError.General(msg: "Invalid apply")
}
}
}
// print
func PRINT(exp: MalVal) -> String {
return pr_str(exp, true)
}
// repl
func rep(str:String) throws -> String {
return PRINT(try EVAL(try READ(str), repl_env))
}
var repl_env: Env = try Env()
// core.swift: defined using Swift
for (k, fn) in core_ns {
try repl_env.set(MalVal.MalSymbol(k), malfunc(fn))
}
try repl_env.set(MalVal.MalSymbol("eval"),
malfunc({ try EVAL($0[0], repl_env) }))
let pargs = Process.arguments.map { MalVal.MalString($0) }
// TODO: weird way to get empty list, fix this
var args = pargs[pargs.startIndex..<pargs.startIndex]
if pargs.startIndex.advancedBy(2) < pargs.endIndex {
args = pargs[pargs.startIndex.advancedBy(2)..<pargs.endIndex]
}
try repl_env.set(MalVal.MalSymbol("*ARGV*"), list(Array(args)))
// core.mal: defined using the language itself
try rep("(def! not (fn* (a) (if a false true)))")
try rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
if Process.arguments.count > 1 {
try rep("(load-file \"" + Process.arguments[1] + "\")")
exit(0)
}
while true {
print("user> ", terminator: "")
let line = readLine(stripNewline: true)
if line == nil { break }
if line == "" { continue }
do {
print(try rep(line!))
} catch (MalError.Reader(let msg)) {
print("Error: \(msg)")
} catch (MalError.General(let msg)) {
print("Error: \(msg)")
}
}
| mpl-2.0 | 075d74ef4bc0ebf33b95a3b0051f4ecd | 31.446667 | 89 | 0.517978 | 3.778727 | false | false | false | false |
coach-plus/ios | Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift | 6 | 5199 | //
// DistinctUntilChanged.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where Element: Equatable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> Observable<Element> {
return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
}
}
extension ObservableType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Observable<Element> {
return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 })
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool)
-> Observable<Element> {
return self.distinctUntilChanged({ $0 }, comparer: comparer)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Observable<Element> {
return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer)
}
}
final private class DistinctUntilChangedSink<Observer: ObserverType, Key>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
private let _parent: DistinctUntilChanged<Element, Key>
private var _currentKey: Key?
init(parent: DistinctUntilChanged<Element, Key>, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
do {
let key = try self._parent._selector(value)
var areEqual = false
if let currentKey = self._currentKey {
areEqual = try self._parent._comparer(currentKey, key)
}
if areEqual {
return
}
self._currentKey = key
self.forwardOn(event)
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
case .error, .completed:
self.forwardOn(event)
self.dispose()
}
}
}
final private class DistinctUntilChanged<Element, Key>: Producer<Element> {
typealias KeySelector = (Element) throws -> Key
typealias EqualityComparer = (Key, Key) throws -> Bool
private let _source: Observable<Element>
fileprivate let _selector: KeySelector
fileprivate let _comparer: EqualityComparer
init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) {
self._source = source
self._selector = selector
self._comparer = comparer
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | 62c9d4ca4e30e17123f680f8901b16ca | 40.584 | 171 | 0.664871 | 5.182453 | false | false | false | false |
GianniCarlo/Audiobook-Player | Shared/BookSortService+SortError+PlayListSortOrder.swift | 1 | 1959 | import Foundation
public final class BookSortService {
public class func sort(_ books: NSOrderedSet, by type: PlayListSortOrder) -> NSOrderedSet {
switch type {
case .metadataTitle, .fileName:
let sortDescriptor = self.getSortDescriptor(by: type)
return self.sort(books, by: type.rawValue, sortDescriptors: [sortDescriptor])
case .mostRecent:
let sortDescriptor = self.getSortDescriptor(by: type, ascending: false)
return self.sort(books, by: type.rawValue, sortDescriptors: [sortDescriptor])
case .reverseOrder:
return books.reversed
}
}
/// Get sort descriptor for book sorting
/// - Parameters:
/// - type: Type of sorting to be performed / Sort using attribute key
/// - ascending: Ascending / Descending sort descriptor (Default: true)
/// - Returns: Sort descriptor for the sort order type
private class func getSortDescriptor(by type: PlayListSortOrder, ascending: Bool = true) -> NSSortDescriptor {
switch type {
case .mostRecent:
return NSSortDescriptor(key: type.rawValue, ascending: ascending, selector: #selector(NSDate.compare(_:)))
default:
return NSSortDescriptor(key: type.rawValue, ascending: ascending, selector: #selector(NSString.localizedStandardCompare(_:)))
}
}
private class func sort(_ books: NSOrderedSet, by key: String, sortDescriptors: [NSSortDescriptor] = []) -> NSOrderedSet {
let sortedBooks = books.sortedArray(using: sortDescriptors)
return NSOrderedSet(array: sortedBooks)
}
}
enum SortError: Error {
case missingOriginalFilename,
invalidType
}
public enum PlayListSortOrder: String {
case metadataTitle = "title"
case fileName = "originalFileName"
case mostRecent = "lastPlayDate"
case reverseOrder
}
protocol Sortable {
func sort(by sortType: PlayListSortOrder)
}
| gpl-3.0 | d679f549e7026a1f96a367a71aa501cf | 37.411765 | 137 | 0.677386 | 4.84901 | false | false | false | false |
haawa799/WaniKit2 | Sources/WaniKit/Model/WordlInfo.swift | 2 | 972 | //
// WordlInfo.swift
// Pods
//
// Created by Andriy K. on 2/17/16.
//
//
import Foundation
public struct WordInfo {
// Dictionary keys
private static let keyCharacter = "character"
private static let keyKana = "kana"
private static let keyMeaning = "meaning"
private static let keyLevel = "level"
private static let keyUserSpecific = "user_specific"
public var character: String
public var kana: String?
public var meaning: String?
public var level: Int
public var userSpecific: UserSpecific?
}
extension WordInfo: DictionaryInitialization {
public init(dict: NSDictionary) {
character = dict[WordInfo.keyCharacter] as! String
meaning = dict[WordInfo.keyMeaning] as? String
kana = dict[WordInfo.keyKana] as? String
level = dict[WordInfo.keyLevel] as! Int
if let userSpecificDict = dict[WordInfo.keyUserSpecific] as? NSDictionary {
userSpecific = UserSpecific(dict: userSpecificDict)
}
}
} | mit | 140610072c67ab4f70a0f8fa18cca87d | 22.731707 | 79 | 0.70679 | 4.066946 | false | false | false | false |
ladanv/EmailNotifier | EmailNotifier/AppDelegate.swift | 1 | 2653 | //
// AppDelegate.swift
// EmailNotifier
//
// Created by Vitaliy.Ladan on 07.12.14.
// Copyright (c) 2014 Vitaliy.Ladan. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var emailListPopover: NSPopover!
let emptyMailboxIcon = "Gray-Mailbox-32"
let fullMailboxIcon = "Black-Mailbox-32"
var statusItem : NSStatusItem!
var blingIconCounter = 0
var blingIconTimer: NSTimer?
func applicationDidFinishLaunching(aNotification: NSNotification) {
initStatusItem()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notifyUser", name: "notifyUser", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resetStatusIcon", name: "resetStatusIcon", object: nil)
}
func applicationWillTerminate(aNotification: NSNotification) {
}
func initStatusItem() {
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
statusItem.image = NSImage(named: emptyMailboxIcon)
statusItem.highlightMode = false
statusItem.target = self
statusItem.action = "togglePopover:"
}
func togglePopover(sender: AnyObject) {
emailListPopover.showRelativeToRect(sender.bounds, ofView: statusItem.button!, preferredEdge: NSMaxYEdge)
}
func notifyUser() {
if statusItem.image?.name() == emptyMailboxIcon {
if emailListPopover.shown {
statusItem.image = NSImage(named: fullMailboxIcon)
return
}
if let timer = blingIconTimer {
if !timer.valid {
startBlingingIcon()
}
} else {
startBlingingIcon()
}
}
}
func startBlingingIcon() {
blingIconCounter = 5 * 2 // bling 5 times, 2 times with black icon and 2 times with gray
blingIconTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "blingIcon", userInfo: nil, repeats: true)
}
func blingIcon() {
if blingIconCounter == 0 {
stopBlingingIcon()
}
let iconName = blingIconCounter % 2 == 0 ? fullMailboxIcon : emptyMailboxIcon
statusItem.image = NSImage(named: iconName)
blingIconCounter--
}
func stopBlingingIcon() {
if let timer = blingIconTimer {
timer.invalidate()
}
}
func resetStatusIcon() {
stopBlingingIcon()
statusItem.image = NSImage(named: emptyMailboxIcon)
}
}
| mit | 847d2eee0b777c641c274f7038a1a57b | 30.211765 | 133 | 0.626084 | 5.181641 | false | false | false | false |
27629678/NetworkPragraming | UnitTesting/UnitTesting.swift | 1 | 2222 | //
// UnitTesting.swift
// UnitTesting
//
// Created by hzyuxiaohua on 2017/4/8.
// Copyright © 2017年 hzyuxiaohua. All rights reserved.
//
import XCTest
class UnitTesting: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCFNetworkUtil() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
var errCode: CFNetworkErrorCode = .noError
let adrs = CFNetworkUtil.addresses(forHost: "www.baidu.com", errCode: &errCode)
if errCode != .noError {
XCTAssert(false)
}
else {
print("\(String(describing: adrs))")
}
let names = CFNetworkUtil.hostNames(forAddress: "14.215.177.37", errCode: &errCode);
if errCode != .noError {
// WARN: Can not pass through this unit test
XCTAssert(false)
}
else {
print("\(String(describing: names))")
}
}
func testCFSocketServer() {
let server = CFSocketServer()
server.listen(onPort: 2018)
if server.errCode != .noError {
XCTAssert(false)
return
}
}
func testCFSocketClient() {
guard NetworkDetect.connectType() != .none else {
return
}
let client = CFSocketClient()
client.connect(to: "0.0.0.0", port: 2017)
XCTAssert(client.errCode == .noError)
_ = client.write(text: "hello, socket")
RunLoop.current.run(until: Date.init(timeIntervalSinceNow: 30))
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit | b723261e4121eca527419b0cb9ccae89 | 26.395062 | 111 | 0.55881 | 4.711253 | false | true | false | false |
danielsanfr/hackatruck-apps-project | HACKATRUCK Apps/AppDetailView.swift | 1 | 1360 | //
// AppDetailVIew.swift
// HACKATRUCK Apps
//
// Created by Student on 3/8/17.
// Copyright © 2017 Daniel San. All rights reserved.
//
import UIKit
class AppDetailView: UIView {
@IBOutlet weak var appDescription: UILabel!
@IBOutlet weak var company: UILabel!
@IBOutlet weak var category: UILabel!
@IBOutlet weak var team: UILabel!
@IBOutlet weak var createdAt: UILabel!
@IBOutlet weak var university: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func bind(_ app: App) {
appDescription.text = app.appDescription
company.text = app.company
university.text = app.university
category.text = app.category.name
var team = ""
for developer in app.developers {
team += developer + ", "
}
let index = team.index(team.endIndex, offsetBy: -2)
self.team.text = team.substring(to: index)
if let createdAtDate = app.createdAt {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MMM/yyyy - hh:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_EU")
createdAt.text = "\(dateFormatter.string(from: createdAtDate))"
}
}
}
| unlicense | d1deef520265151f35ef37fc33660c98 | 27.3125 | 75 | 0.621045 | 4.143293 | false | false | false | false |
material-motion/motion-transitions-objc | tests/unit/MockTransitionContext.swift | 1 | 1488 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
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 MotionTransitions
import XCTest
class MockTransitionContext: TransitionContext {
init() {
foreViewController.view.frame = containerView.bounds
backViewController.view.frame = containerView.bounds
}
func compose(with transition: Transition) {
transition.start(with: self)
}
var transitionDidEndExpectation: XCTestExpectation?
func transitionDidEnd() {
transitionDidEndExpectation?.fulfill()
}
var direction: TransitionDirection = .forward
var duration: TimeInterval = 0.1
var sourceViewController: UIViewController? = nil
var backViewController = UIViewController()
var foreViewController = UIViewController()
var containerView = UIView(frame: .init(x: 0, y: 0, width: 200, height: 500))
var presentationController: UIPresentationController? = nil
func `defer`(toCompletion work: @escaping () -> Void) {
}
}
| apache-2.0 | 73c2eefedb96874d3bcf1e7ad318f00b | 26.555556 | 79 | 0.759409 | 4.708861 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/Messages/WhenMessagesSceneTapsLogoutButton_MessagesPresenterShould.swift | 1 | 2489 | import EurofurenceApplication
import EurofurenceModel
import XCTest
class WhenMessagesSceneTapsLogoutButton_MessagesPresenterShould: XCTestCase {
func testTellTheDelegateToShowTheLoggingOutAlert() {
let context = MessagesPresenterTestContext.makeTestCaseForAuthenticatedUser()
context.scene.delegate?.messagesSceneReady()
context.scene.delegate?.messagesSceneDidTapLogoutButton()
XCTAssertTrue(context.delegate.wasToldToShowLoggingOutAlert)
}
func testTellTheAuthenticationServiceToLogoutWhenTheLoginAlertIsPresented() {
let context = MessagesPresenterTestContext.makeTestCaseForAuthenticatedUser()
context.scene.delegate?.messagesSceneReady()
context.scene.delegate?.messagesSceneDidTapLogoutButton()
context.delegate.capturedAlertPresentedBlock?({})
XCTAssertTrue(context.authenticationService.wasToldToLogout)
}
func testInvokeTheAlertDismissalBlockWhenAuthenticationServiceFinishes() {
let context = MessagesPresenterTestContext.makeTestCaseForAuthenticatedUser()
context.scene.delegate?.messagesSceneReady()
context.scene.delegate?.messagesSceneDidTapLogoutButton()
var didInvokeDismissalHandlerForPresentedLogoutAlert = false
context.delegate.capturedAlertPresentedBlock?({ didInvokeDismissalHandlerForPresentedLogoutAlert = true })
context.authenticationService.capturedLogoutHandler?(.success)
XCTAssertTrue(didInvokeDismissalHandlerForPresentedLogoutAlert)
}
func testTellTheDelegateToDismissTheMessagesModuleWhenLogoutSucceeds() {
let context = MessagesPresenterTestContext.makeTestCaseForAuthenticatedUser()
context.scene.delegate?.messagesSceneReady()
context.scene.delegate?.messagesSceneDidTapLogoutButton()
context.delegate.capturedAlertPresentedBlock?({})
context.authenticationService.capturedLogoutHandler?(.success)
XCTAssertTrue(context.delegate.dismissed)
}
func testTellTheDelegateToShowTheLogoutFailedAlertWhenLogoutSucceeds() {
let context = MessagesPresenterTestContext.makeTestCaseForAuthenticatedUser()
context.scene.delegate?.messagesSceneReady()
context.scene.delegate?.messagesSceneDidTapLogoutButton()
context.delegate.capturedAlertPresentedBlock?({})
context.authenticationService.capturedLogoutHandler?(.failure)
XCTAssertTrue(context.delegate.wasToldToShowLogoutFailedAlert)
}
}
| mit | 36656abc8ea23572ab5281baecdc296f | 44.254545 | 114 | 0.788268 | 6.481771 | false | true | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/07632-resolvetypedecl.swift | 11 | 302 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T where T.Element == g: d = "\(e : A? {
func b<T: A"\(e = c<I : e: B<T.B == e: T>
protocol A : NSObject {
typealias e : B
le
| mit | a1a27c68d46b1a37317825f925324fb4 | 32.555556 | 87 | 0.665563 | 3.178947 | false | true | false | false |
open-telemetry/opentelemetry-swift | Sources/Importers/OpenTracingShim/SpanShim.swift | 1 | 5341 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryApi
import Opentracing
public class SpanShim: OTSpan, BaseShimProtocol {
static let defaultEventName = "log"
static let OpenTracingErrorTag = "error"
static let OpenTracingEventField = "event"
public private(set) var span: Span
var telemetryInfo: TelemetryInfo
init(telemetryInfo: TelemetryInfo, span: Span) {
self.telemetryInfo = telemetryInfo
self.span = span
}
public func context() -> OTSpanContext {
var contextShim = spanContextTable.get(spanShim: self)
if contextShim == nil {
contextShim = spanContextTable.create(spanShim: self)
}
return contextShim!
}
public func tracer() -> OTTracer {
return TraceShim.instance.otTracer
}
public func setOperationName(_ operationName: String) {
span.name = operationName
}
public func setTag(_ key: String, value: String) {
if key == SpanShim.OpenTracingErrorTag {
let error = Bool(value) ?? false
span.status = error ? .error(description: "error") : .ok
} else {
span.setAttribute(key: key, value: value)
}
}
public func setTag(_ key: String, numberValue value: NSNumber) {
let numberType = CFNumberGetType(value)
switch numberType {
case .charType:
span.setAttribute(key: key, value: value.boolValue)
case .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type, .shortType, .intType, .longType, .longLongType, .cfIndexType, .nsIntegerType:
span.setAttribute(key: key, value: value.intValue)
case .float32Type, .float64Type, .floatType, .doubleType, .cgFloatType:
span.setAttribute(key: key, value: value.doubleValue)
@unknown default:
span.setAttribute(key: key, value: value.doubleValue)
}
}
public func setTag(_ key: String, boolValue value: Bool) {
if key == SpanShim.OpenTracingErrorTag {
span.status = value ? .error(description: "error") : .ok
} else {
span.setAttribute(key: key, value: value)
}
}
public func log(_ fields: [String: NSObject]) {
span.addEvent(name: SpanShim.getEventNameFrom(fields: fields), attributes: SpanShim.convertToAttributes(fields: fields))
}
public func log(_ fields: [String: NSObject], timestamp: Date?) {
span.addEvent(name: SpanShim.getEventNameFrom(fields: fields), attributes: SpanShim.convertToAttributes(fields: fields), timestamp: timestamp ?? Date())
}
public func logEvent(_ eventName: String) {
span.addEvent(name: eventName)
}
public func logEvent(_ eventName: String, payload: NSObject?) {
if let object = payload {
span.addEvent(name: eventName, attributes: SpanShim.convertToAttributes(fields: [eventName: object]))
} else {
span.addEvent(name: eventName)
}
}
public func log(_ eventName: String, timestamp: Date?, payload: NSObject?) {
if let object = payload {
span.addEvent(name: eventName, attributes: SpanShim.convertToAttributes(fields: [eventName: object]), timestamp: timestamp ?? Date())
} else {
span.addEvent(name: eventName, timestamp: timestamp ?? Date())
}
}
public func setBaggageItem(_ key: String, value: String) -> OTSpan {
spanContextTable.setBaggageItem(spanShim: self, key: key, value: value)
return self
}
public func getBaggageItem(_ key: String) -> String? {
return spanContextTable.getBaggageItem(spanShim: self, key: key)
}
public func finish() {
span.end()
}
public func finish(withTime finishTime: Date?) {
if let finishTime = finishTime {
span.end(time: finishTime)
} else {
span.end()
}
}
static func getEventNameFrom(fields: [String: NSObject]) -> String {
return fields[OpenTracingEventField]?.description ?? defaultEventName
}
static func convertToAttributes(fields: [String: NSObject]) -> [String: AttributeValue] {
let attributes: [String: AttributeValue] = fields.mapValues { value in
if (value as? NSString) != nil {
return AttributeValue.string(value as! String)
} else if (value as? NSNumber) != nil {
let number = value as! NSNumber
let numberType = CFNumberGetType(number)
switch numberType {
case .charType:
return AttributeValue.bool(number.boolValue)
case .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type, .shortType, .intType, .longType, .longLongType, .cfIndexType, .nsIntegerType:
return AttributeValue.int(number.intValue)
case .float32Type, .float64Type, .floatType, .doubleType, .cgFloatType:
return AttributeValue.double(number.doubleValue)
@unknown default:
return AttributeValue.double(number.doubleValue)
}
} else {
return AttributeValue.string("")
}
}
return attributes
}
}
| apache-2.0 | 30776e781467a34eeae58d37cfb7dc88 | 34.845638 | 160 | 0.619734 | 4.450833 | false | false | false | false |
naokits/AWSiOSExamples | AWSiOSExamples/MasterViewController.swift | 1 | 2887 | //
// MasterViewController.swift
// AWSiOSExamples
//
// Created by naokits on 7/19/15.
// Copyright (c) 2015 Naoki Tsutsui. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var objects = [AnyObject]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as! NSDate
(segue.destinationViewController as! DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit | 71cd8c2766d7d4af273ce9c41fd3781c | 32.964706 | 157 | 0.682716 | 5.436911 | false | false | false | false |
michaelarmstrong/SuperMock | Pod/Classes/SuperMockResponseHelper.swift | 1 | 15304 | //
// SuperMockResponseHelper.swift
// SuperMock
//
// Created by Michael Armstrong on 02/11/2015.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Foundation
public enum RecordPolicy : String {
case Override = "Override"
case Record = "Record"
}
class SuperMockResponseHelper: NSObject {
static let sharedHelper = SuperMockResponseHelper()
fileprivate let maxFileLegth = 30
var mocking = false
var mocksFile = "Mocks.plist"
fileprivate let dataKey = "data"
fileprivate let responseKey = "response"
fileprivate var fileslist: [String] = []
class var bundleForMocks : Bundle? {
set {
sharedHelper.bundle = newValue
}
get {
return sharedHelper.bundle
}
}
let fileManager = FileManager.default
var bundle : Bundle? {
didSet {
loadDefinitions()
}
}
/**
Automatically populated by Mocks.plist. A dictionary containing mocks loaded in from Mocks.plist, purposely not made private as can be modified at runtime to
provide alternative mocks for URL's on subsequent requests. Better support for this feature is coming in the future.
*/
var mocks: NSMutableDictionary = [:]
/**
Automatically populated by Mocks.plist. Dictionary containing all the associated and supported mime.types for mocks. Defaults to text/plain if none provided.
*/
var mimes = Dictionary<String,String>()
enum RequestMethod : String {
case POST = "POST"
case GET = "GET"
case PUT = "PUT"
case DELETE = "DELETE"
}
var recordPolicy = RecordPolicy.Record
var recording = false
func loadDefinitions() {
guard let bundle = bundle else {
fatalError("You must provide a bundle via NSBundle(class:) or NSBundle.mainBundle() before continuing.")
}
if let definitionsPath = bundle.path(forResource: mocksFile, ofType: nil),
let definitions = NSDictionary(contentsOfFile: definitionsPath),
let mocks = definitions["mocks"] as? [String: Any],
let mimes = definitions["mimes"] as? Dictionary<String,String> {
self.mocks = NSMutableDictionary(dictionary: mocks)
self.mimes = mimes
}
}
/**
Public method to construct and return (when needed) mock NSURLRequest objects.
- parameter request: the original NSURLRequest to provide a mock for.
- returns: NSURLRequest with manipulated resource identifier.
*/
func mockRequest(_ request: URLRequest) -> URLRequest {
let method = request.httpMethod ?? "GET"
let requestMethod = RequestMethod(rawValue: method) ?? .GET
let mockURL = mockURLForRequestURL(request.url!, requestMethod: requestMethod, mocks: mocks)
if mockURL == request.url {
return request
}
let mocked = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
mocked.url = mockURL
mocked.setValue("true", forHTTPHeaderField: "X-SUPERMOCK-MOCKREQUEST")
let injectableRequest = mocked.copy() as! URLRequest
return injectableRequest
}
fileprivate func mockURLForRequestURL(_ url: URL, requestMethod: RequestMethod, mocks: NSMutableDictionary) -> URL? {
return mockURLForRequestURL(url, requestMethod: requestMethod, mocks: mocks, isData: true)
}
fileprivate func mockURLForRequestRestponseURL(_ url: URL, requestMethod: RequestMethod, mocks: NSMutableDictionary) -> URL? {
return mockURLForRequestURL(url, requestMethod: requestMethod, mocks: mocks, isData: false)
}
fileprivate func mockURLForRequestURL(_ url: URL, requestMethod: RequestMethod, mocks: NSMutableDictionary, isData: Bool) -> URL? {
guard let definitionsForMethod = mocks[requestMethod.rawValue] as? NSDictionary else {
fatalError("Couldn't find definitions for request: \(requestMethod) make sure to create a node for it in the plist")
}
if let responseFiles = definitionsForMethod[url.absoluteString] as? NSMutableArray,
let responseFileDictionary = responseFiles.firstObject as? [String: String] {
if let responseFile = responseFileDictionary[dataKey],
let responsePath = bundle?.path(forResource: responseFile, ofType: ""),
isData {
return URL(fileURLWithPath: responsePath)
}
if let responseFile = responseFileDictionary[responseKey],
let responsePath = bundle?.path(forResource: responseFile, ofType: ""),
!isData {
if responseFiles.count > 1 {
let reducedResponsesArray = NSMutableArray(array: responseFiles)
reducedResponsesArray.removeObject(at: 0)
let requestMocks = mocks["\(requestMethod)"] as? NSDictionary ?? [:]
let mutableMocks = NSMutableDictionary(dictionary: requestMocks)
mutableMocks["\(url)"] = reducedResponsesArray
self.mocks["\(requestMethod)"] = mutableMocks
}
return URL(fileURLWithPath: responsePath)
}
}
return url
}
/**
Public method to return data for associated mock requests.
Will fail with a fatalError if called for items that are not represented on the local filesystem.
- parameter request: the mock NSURLRequest object.
- returns: NSData containing the mock response.
*/
func responseForMockRequest(_ request: URLRequest!) -> Data? {
if request.url?.isFileURL == false {
return nil// fatalError("You should only call this on mocked URLs")
}
return mockedResponse(request.url!)
}
/**
Public method to return associated mimeTypes from the Mocks.plist configuration.
Always returns a value. Defaults to "text/plain"
- parameter url: Any NSURL object for which a mime.type is to be obtained.
- returns: String containing RFC 6838 compliant mime.type
*/
func mimeType(_ url: URL!) -> String {
let pathExtension = url.pathExtension
if let mime = mimes[pathExtension] {
return mime
}
return "text/plain"
}
fileprivate func mockedResponse(_ url: URL) -> Data? {
if let data = try? Data(contentsOf: url) {
return data
}
return nil
}
/**
Record the data and save it in the mock file in the documents directory. The data is saved in a file with extension based on the mime of the request, the file name is unique dependent on the url of the request. The Mock file contains the request and the file name for the request data response.
:param: data data to save into the file
:param: request Rapresent the request called for obtain the data
*/
func recordDataForRequest(_ data: Data?, httpHeaders: [AnyHashable: Any]?, request: URLRequest) {
guard let headers = httpHeaders
else { return }
var headersData = try? JSONSerialization.data(withJSONObject: headers, options: .prettyPrinted)
if headersData == nil {
headersData = NSKeyedArchiver.archivedData(withRootObject: headers)
}
recordForRequest(data,
headers:headersData,
request: request)
}
fileprivate func recordForRequest(_ data: Data?, headers: Data?, request: URLRequest) {
guard let definitionsPath = mockFileOutOfBundle(),
let definitions = NSMutableDictionary(contentsOfFile: definitionsPath),
let httpMethod = request.httpMethod,
let url = request.url,
let responseFile = generateResponseFileName(url),
let responsePath = mockedFilePath(responseFile),
let headersFile = generateResponseHeadersFileName(url),
let headersPath = mockedFilePath(headersFile),
let data = data else {
return
}
do { try data.write(to: URL(fileURLWithPath: responsePath), options: [.atomic])
try headers?.write(to: URL(fileURLWithPath: headersPath), options: [.atomic]) }
catch { print("SuperMock - error writing in file: \(error)")}
let keyPath = "mocks.\(httpMethod).\(url)"
if let mocks = definitions.value(forKeyPath: keyPath) as? NSMutableArray {
mocks.add([dataKey:responseFile, responseKey:headersFile])
if !definitions.write(toFile: definitionsPath, atomically: true) {
print("Error writning the file, permission problems?")
}
} else if let mocks = definitions.value(forKeyPath: "mocks.\(httpMethod)") as? NSMutableDictionary {
mocks["\(url)"] = [[dataKey:responseFile, responseKey:headersFile]]
if !definitions.write(toFile: definitionsPath, atomically: true) {
print("Error writning the file, permission problems?")
}
}
}
/**
Return the mock HTTP Response based on the saved HTTP Headers into the specific file, it create the response with the previous Response header
- parameter request: Represent the request (orginal not mocked) callled for obtain the data
- returns: Mocked response set with the HTTPHEaders of the response recorded
*/
func mockResponse(_ request: URLRequest) -> URLResponse? {
let method = request.httpMethod ?? "GET"
let requestMethod = RequestMethod(rawValue: method) ?? .GET
guard let mockedHeaderFields = mockedHeaderFields(request.url!, requestMethod: requestMethod, mocks: mocks) else {
return nil
}
var statusCode = 200
if let statusString = mockedHeaderFields["status"], let responseStatus = Int(statusString) {
statusCode = responseStatus
}
let mockedResponse = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: mockedHeaderFields )
return mockedResponse
}
fileprivate func mockedHeaderFields(_ url: URL, requestMethod: RequestMethod, mocks: NSMutableDictionary) -> [String : String]? {
guard let mockedHeaderFieldsURL = mockURLForRequestRestponseURL(url, requestMethod: requestMethod, mocks: mocks), mockedHeaderFieldsURL != url else {
return nil
}
guard let mockedHeaderFieldData = try? Data(contentsOf: mockedHeaderFieldsURL) else {
return nil
}
if let mockedHeaderFields = try? JSONSerialization.jsonObject(with: mockedHeaderFieldData, options: .allowFragments) as? [String : String] {
return mockedHeaderFields
}
guard let mockedHeaderFields = NSKeyedUnarchiver.unarchiveObject(with: mockedHeaderFieldData) as? [String : String] else {
return nil
}
return mockedHeaderFields
}
}
// MARK: File extension
extension SuperMockResponseHelper {
fileprivate func fileType(_ mimeType: String) -> String {
switch (mimeType) {
case "text/plain":
return "txt"
case "text/html":
return "html"
case "application/json":
return "json"
default:
return "txt"
}
}
fileprivate func mockedFilePath(_ fileName: String?)->String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths[0] as? String
guard let fileName = fileName else {
return nil
}
let filePath = (documentsDirectory)! + "/\(fileName)"
print("Mocked response recorded in: \(filePath)")
return filePath
}
fileprivate func generateResponseFileName(_ url: URL)->String? {
return generateResponseFileName(url, isData: true)
}
fileprivate func generateResponseHeadersFileName(_ url: URL)->String? {
return generateResponseFileName(url, isData: false)
}
fileprivate func generateResponseFileName(_ url: URL, isData:Bool)->String? {
var urlString = url.absoluteString
let urlStringLengh = urlString.count
let fromIndex = (urlStringLengh > maxFileLegth) ? maxFileLegth : urlStringLengh
urlString = urlString.suffix(fromIndex).debugDescription
guard let fileName = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
fatalError("You must provide a request with a valid URL")
}
var fileCounter = 0
var composedFileName = ""
repeat {
composedFileName = fileName + "-\(fileCounter)"
fileCounter += 1
}
while (fileslist.contains(composedFileName))
fileslist.append(composedFileName)
if isData && recording {
return composedFileName + "DATA." + fileType(mimeType(url))
}
return composedFileName + "." + fileType(mimeType(url))
}
func mockFileOutOfBundle() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
guard let bundle = bundle,
let documentsDirectory = paths[0] as? String else {
return nil
}
try? FileManager.default.createDirectory(atPath: documentsDirectory, withIntermediateDirectories: true, attributes: nil)
let mocksPath = (documentsDirectory) + "/" + mocksFile
print("Recording mocks at: \(mocksPath)")
if !FileManager.default.fileExists(atPath: mocksPath),
let definitionsPath = bundle.path(forResource: mocksFile, ofType: nil),
let definitions = NSMutableDictionary(contentsOfFile: definitionsPath) {
definitions.write(toFile: mocksPath, atomically: true)
} else if !FileManager.default.fileExists(atPath: mocksPath) {
let mockDictionary = NSDictionary(dictionary:["mimes":["htm":"text/html",
"html":"text/html",
"json":"application/json"],
"mocks":["DELETE":["http://":[["data":"", "response":""]]],
"POST":["http://":[["data":"", "response":""]]],
"PUT":["http://":[["data":"", "response":""]]],
"GET":["http://":[["data":"", "response":""]]]]])
if !mockDictionary.write(toFile: mocksPath, atomically: true) {
print("There was an error creating the file")
}
}
return mocksPath
}
}
| mit | 1d0987c9381a955148194d48236e84fa | 39.484127 | 299 | 0.61073 | 5.481017 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/Node+Hierarchy.swift | 1 | 8100 | //
// Node+Children.swift
// Fiber2D
//
// Created by Andrey Volodin on 27.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public extension Node {
// MARK: Hierarchy
/// @name Working with Node Trees
/** A weak reference to the parent. */
public var parent: Node? {
get { return _parent }
set {
if _parent != nil {
removeFromParent(cleanup: false)
}
_parent = newValue
parent?.add(child: self)
}
}
/**
Adds a child to the container with z order and tag.
If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
@param node Node to add as a child.
@param z Draw order of node. This value will be assigned to the node's zOrder property.
@param name Name for this node. This string will be assigned to the node's name property.
@see zOrder
@see name
@note "add" logic MUST only be on this method
* If a class want's to extend the 'add child' behaviour it only needs
* to override this method
*/
public func add(child: Node, z: Int? = nil, name: String? = nil) {
assert(child.parent == nil, "child already added to another node. It can't be added again")
assert((child as? Scene) == nil, "Scenes may not be added as children of other nodes or scenes. Only one scene can exist in a hierarchy.")
child.zOrder = z ?? child.zOrder
child.name = name ?? child.name
child._parent = self
// this is needed for the case when node has Normalize positon type and switched parents
// we should've add method `parentContentSizeChanged` and trigger that instead
child.isTransformDirty = true
children.append(child)
self.isReorderChildDirty = true
// Update pausing parameters
child.pausedAncestors = pausedAncestors + (paused ? 1 : 0)
child.recursivelyIncrementPausedAncestors(child.pausedAncestors)
if isInActiveScene {
child._onEnter()
child._onEnterTransitionDidFinish()
}
childWasAdded(child: child)
Director.currentDirector!.responderManager.markAsDirty()
}
/** Removes the node from its parent node. Will stop the node's scheduled selectors/blocks and actions.
@note It is typically more efficient to change a node's visible status rather than remove + add(child: if all you need
is to temporarily remove the node from the screen.
@see visible */
public func removeFromParent(cleanup: Bool = true) {
parent?.remove(child: self, cleanup: cleanup)
}
/**
Removes a child from the container. The node must be a child of this node.
Will stop the node's scheduled selectors/blocks and actions.
@note It is recommended to use `[node removeFromParent]` over `[self removeChild:node]` as the former will always work,
even in cases where (in this example) the node hierarchy has changed so that node no longer is a child of self.
@note It is typically more efficient to change a node's visible status rather than remove + add(child: if all you need
is to temporarily remove the node from the screen.
@param child The child node to remove.
@see removeFromParent
*/
public func remove(child: Node, cleanup: Bool = true) {
detach(child: child, cleanup: cleanup)
}
/**
Removes a child from the container by name. Does nothing if there's no node with that name.
Will stop the node's scheduled selectors/blocks and actions.
@param name Name of node to be removed.
*/
public func removeChild(by name: String, cleanup: Bool = true) {
guard let child = getChild(by: name, recursively: false) else {
print("WARNING: Node doesn't contain specified child")
return
}
detach(child: child, cleanup: cleanup)
}
/**
Removes all children from the container.
@note It is unnecessary to call this when replacing scenes or removing nodes. All nodes call this method on themselves automatically
when removed from a parent node or when a new scene is presented.
*/
public func removeAllChildren(cleanup: Bool = true) {
// not using detachChild improves speed here
for c: Node in children {
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if self.isInActiveScene {
c._onExitTransitionDidStart()
c._onExit()
}
c.recursivelyIncrementPausedAncestors(-c.pausedAncestors)
c.pausedAncestors = 0
if cleanup {
c.cleanup()
}
// set parent nil at the end (issue #476)
c.parent = nil
Director.currentDirector!.responderManager.markAsDirty()
}
children.removeAll()
}
/** final method called to actually remove a child node from the children.
* @param node The child node to remove
* @param cleanup Stops all scheduled events and actions
*/
public func detach(child: Node, cleanup doCleanup: Bool) {
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if self.isInActiveScene {
child._onExitTransitionDidStart()
child._onExit()
}
child.recursivelyIncrementPausedAncestors(-child.pausedAncestors)
child.pausedAncestors = 0
// If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if doCleanup {
child.cleanup()
}
// set parent nil at the end (issue #476)
child._parent = nil
Director.currentDirector!.responderManager.markAsDirty()
children.removeObject(child)
childWasRemoved(child: child)
}
/** performance improvement, Sort the children array once before drawing, instead of every time when a child is added or reordered
don't call this manually unless a child added needs to be removed in the same frame */
internal func sortAllChildren() {
if isReorderChildDirty {
children.sort { $0.zOrder < $1.zOrder }
//don't need to check children recursively, that's done in visit of each child
self.isReorderChildDirty = false
Director.currentDirector!.responderManager.markAsDirty()
}
}
/// Recursively get a child by name, but don't return the root of the search.
private func getChildRecursive(by name: String, root: Node) -> Node? {
if self !== root && (name == name) { return self }
for node in children {
let n = node.getChildRecursive(by: name, root: root)
if n != nil {
return n
}
}
// not found
return nil
}
/**
Search through the children of the container for one matching the name tag.
If recursive, it returns the first matching node, via a depth first search.
Otherwise, only immediate children are checked.
@note Avoid calling this often, ie multiple times per frame, as the lookup cost can add up. Specifically if the search is recursive.
@param name The name of the node to look for.
@param isRecursive Search recursively through node's children (its node tree).
@return Returns the first node with a matching name, or nil if no node with that name was found.
@see name
*/
public func getChild(by name: String, recursively isRecursive: Bool) -> Node? {
if isRecursive {
return self.getChildRecursive(by: name, root: self)
}
else {
for node in children {
if node.name == name {
return node
}
}
}
// not found
return nil
}
}
| apache-2.0 | 0d9956b3fae3890773f93debc0e5fda1 | 38.315534 | 146 | 0.619089 | 4.719697 | false | false | false | false |
ansinlee/meteorology | meteorology/BBSTopic.swift | 1 | 2797 | //
// BBSTopic.swift
// meteorology
//
// Created by LeeAnsin on 15/3/29.
// Copyright (c) 2015年 LeeAnsin. All rights reserved.
//
import Foundation
import UIKit
class Topic {
var Id: Int32?
var Img: String?
var Title: String?
var Abstract:String?
var Time: String?
var Creator: User?
var Content:TopicDetailContent?
init(id: Int32?, img: String?, title: String?, abstract: String?, time:String?, creator:User?, content: TopicDetailContent?) {
self.Id = id
self.Img = img
self.Title = title
self.Abstract = abstract
self.Time = time
self.Creator = creator
self.Content = content
}
init(t: Topic) {
self.Id = t.Id
self.Img = t.Img
self.Title = t.Title
self.Abstract = t.Abstract
self.Time = t.Time
self.Creator = t.Creator
self.Content = t.Content
}
init(data:AnyObject?) {
if data == nil {
return
}
self.Id = (data?.objectForKey("Id") as! NSNumber).intValue
self.Img = data?.objectForKey("Img") as? String
self.Time = GetGoDate(data?.objectForKey("Createtime") as! String)
self.Title = data?.objectForKey("Title") as? String
self.Abstract = data?.objectForKey("Abstract")as? String
self.Content = TopicDetailContent(data: data?.objectForKey("Content"))
self.Creator = User(data: data?.objectForKey("Creator"))
}
}
enum TopicDetailItemType: Int {
case Text = 0
case Image = 1
}
class TopicDetailItem {
var Type: TopicDetailItemType?
var Data: String?
init(type: TopicDetailItemType?, data: String?){
self.Type = type
self.Data = data
}
}
class TopicDetailContent {
var ItemList: [TopicDetailItem]?
init(itemList: [TopicDetailItem]?) {
self.ItemList = itemList
}
init(data:AnyObject?) {
if data == nil {
return
}
self.ItemList = []
var txtFlag = true
var imgFlag = true
if let list = data as? [AnyObject] {
if list.count > 0 {
for i in 0...list.count-1 {
if list[i].objectForKey("type") as! NSNumber == 0 && txtFlag{
self.ItemList?.append(TopicDetailItem(type: TopicDetailItemType.Text, data: list[i].objectForKey("data")as? String))
txtFlag = false
} else if list[i].objectForKey("type") as! NSNumber == 1 && imgFlag {
self.ItemList?.append(TopicDetailItem(type: TopicDetailItemType.Image, data: list[i].objectForKey("data")as? String))
imgFlag = false
}
}
}
}
}
} | apache-2.0 | b7a6b541fe093a835bcdd1c8f46b9194 | 27.824742 | 141 | 0.559213 | 4.146884 | false | false | false | false |
Farteen/firefox-ios | Client/Frontend/Browser/ErrorPageHelper.swift | 5 | 13195 | /* 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
import WebKit
import Shared
class ErrorPageHelper {
static let MozDomain = "mozilla"
static let MozErrorDownloadsNotEnabled = 100
// When an error page is intentionally loaded, its added to this set. If its in the set, we show
// it as an error page. If its not, we assume someone is trying to reload this page somehow, and
// we'll instead redirect back to the original URL.
private static var redirecting = [NSURL]()
class func cfErrorToName(err: CFNetworkErrors) -> String {
switch err {
case .CFHostErrorHostNotFound: return "CFHostErrorHostNotFound"
case .CFHostErrorUnknown: return "CFHostErrorUnknown"
case .CFSOCKSErrorUnknownClientVersion: return "CFSOCKSErrorUnknownClientVersion"
case .CFSOCKSErrorUnsupportedServerVersion: return "CFSOCKSErrorUnsupportedServerVersion"
case .CFSOCKS4ErrorRequestFailed: return "CFSOCKS4ErrorRequestFailed"
case .CFSOCKS4ErrorIdentdFailed: return "CFSOCKS4ErrorIdentdFailed"
case .CFSOCKS4ErrorIdConflict: return "CFSOCKS4ErrorIdConflict"
case .CFSOCKS4ErrorUnknownStatusCode: return "CFSOCKS4ErrorUnknownStatusCode"
case .CFSOCKS5ErrorBadState: return "CFSOCKS5ErrorBadState"
case .CFSOCKS5ErrorBadResponseAddr: return "CFSOCKS5ErrorBadResponseAddr"
case .CFSOCKS5ErrorBadCredentials: return "CFSOCKS5ErrorBadCredentials"
case .CFSOCKS5ErrorUnsupportedNegotiationMethod: return "CFSOCKS5ErrorUnsupportedNegotiationMethod"
case .CFSOCKS5ErrorNoAcceptableMethod: return "CFSOCKS5ErrorNoAcceptableMethod"
case .CFFTPErrorUnexpectedStatusCode: return "CFFTPErrorUnexpectedStatusCode"
case .CFErrorHTTPAuthenticationTypeUnsupported: return "CFErrorHTTPAuthenticationTypeUnsupported"
case .CFErrorHTTPBadCredentials: return "CFErrorHTTPBadCredentials"
case .CFErrorHTTPConnectionLost: return "CFErrorHTTPConnectionLost"
case .CFErrorHTTPParseFailure: return "CFErrorHTTPParseFailure"
case .CFErrorHTTPRedirectionLoopDetected: return "CFErrorHTTPRedirectionLoopDetected"
case .CFErrorHTTPBadURL: return "CFErrorHTTPBadURL"
case .CFErrorHTTPProxyConnectionFailure: return "CFErrorHTTPProxyConnectionFailure"
case .CFErrorHTTPBadProxyCredentials: return "CFErrorHTTPBadProxyCredentials"
case .CFErrorPACFileError: return "CFErrorPACFileError"
case .CFErrorPACFileAuth: return "CFErrorPACFileAuth"
case .CFErrorHTTPSProxyConnectionFailure: return "CFErrorHTTPSProxyConnectionFailure"
case .CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod: return "CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod"
case .CFURLErrorBackgroundSessionInUseByAnotherProcess: return "CFURLErrorBackgroundSessionInUseByAnotherProcess"
case .CFURLErrorBackgroundSessionWasDisconnected: return "CFURLErrorBackgroundSessionWasDisconnected"
case .CFURLErrorUnknown: return "CFURLErrorUnknown"
case .CFURLErrorCancelled: return "CFURLErrorCancelled"
case .CFURLErrorBadURL: return "CFURLErrorBadURL"
case .CFURLErrorTimedOut: return "CFURLErrorTimedOut"
case .CFURLErrorUnsupportedURL: return "CFURLErrorUnsupportedURL"
case .CFURLErrorCannotFindHost: return "CFURLErrorCannotFindHost"
case .CFURLErrorCannotConnectToHost: return "CFURLErrorCannotConnectToHost"
case .CFURLErrorNetworkConnectionLost: return "CFURLErrorNetworkConnectionLost"
case .CFURLErrorDNSLookupFailed: return "CFURLErrorDNSLookupFailed"
case .CFURLErrorHTTPTooManyRedirects: return "CFURLErrorHTTPTooManyRedirects"
case .CFURLErrorResourceUnavailable: return "CFURLErrorResourceUnavailable"
case .CFURLErrorNotConnectedToInternet: return "CFURLErrorNotConnectedToInternet"
case .CFURLErrorRedirectToNonExistentLocation: return "CFURLErrorRedirectToNonExistentLocation"
case .CFURLErrorBadServerResponse: return "CFURLErrorBadServerResponse"
case .CFURLErrorUserCancelledAuthentication: return "CFURLErrorUserCancelledAuthentication"
case .CFURLErrorUserAuthenticationRequired: return "CFURLErrorUserAuthenticationRequired"
case .CFURLErrorZeroByteResource: return "CFURLErrorZeroByteResource"
case .CFURLErrorCannotDecodeRawData: return "CFURLErrorCannotDecodeRawData"
case .CFURLErrorCannotDecodeContentData: return "CFURLErrorCannotDecodeContentData"
case .CFURLErrorCannotParseResponse: return "CFURLErrorCannotParseResponse"
case .CFURLErrorInternationalRoamingOff: return "CFURLErrorInternationalRoamingOff"
case .CFURLErrorCallIsActive: return "CFURLErrorCallIsActive"
case .CFURLErrorDataNotAllowed: return "CFURLErrorDataNotAllowed"
case .CFURLErrorRequestBodyStreamExhausted: return "CFURLErrorRequestBodyStreamExhausted"
case .CFURLErrorFileDoesNotExist: return "CFURLErrorFileDoesNotExist"
case .CFURLErrorFileIsDirectory: return "CFURLErrorFileIsDirectory"
case .CFURLErrorNoPermissionsToReadFile: return "CFURLErrorNoPermissionsToReadFile"
case .CFURLErrorDataLengthExceedsMaximum: return "CFURLErrorDataLengthExceedsMaximum"
case .CFURLErrorSecureConnectionFailed: return "CFURLErrorSecureConnectionFailed"
case .CFURLErrorServerCertificateHasBadDate: return "CFURLErrorServerCertificateHasBadDate"
case .CFURLErrorServerCertificateUntrusted: return "CFURLErrorServerCertificateUntrusted"
case .CFURLErrorServerCertificateHasUnknownRoot: return "CFURLErrorServerCertificateHasUnknownRoot"
case .CFURLErrorServerCertificateNotYetValid: return "CFURLErrorServerCertificateNotYetValid"
case .CFURLErrorClientCertificateRejected: return "CFURLErrorClientCertificateRejected"
case .CFURLErrorClientCertificateRequired: return "CFURLErrorClientCertificateRequired"
case .CFURLErrorCannotLoadFromNetwork: return "CFURLErrorCannotLoadFromNetwork"
case .CFURLErrorCannotCreateFile: return "CFURLErrorCannotCreateFile"
case .CFURLErrorCannotOpenFile: return "CFURLErrorCannotOpenFile"
case .CFURLErrorCannotCloseFile: return "CFURLErrorCannotCloseFile"
case .CFURLErrorCannotWriteToFile: return "CFURLErrorCannotWriteToFile"
case .CFURLErrorCannotRemoveFile: return "CFURLErrorCannotRemoveFile"
case .CFURLErrorCannotMoveFile: return "CFURLErrorCannotMoveFile"
case .CFURLErrorDownloadDecodingFailedMidStream: return "CFURLErrorDownloadDecodingFailedMidStream"
case .CFURLErrorDownloadDecodingFailedToComplete: return "CFURLErrorDownloadDecodingFailedToComplete"
case .CFHTTPCookieCannotParseCookieFile: return "CFHTTPCookieCannotParseCookieFile"
case .CFNetServiceErrorUnknown: return "CFNetServiceErrorUnknown"
case .CFNetServiceErrorCollision: return "CFNetServiceErrorCollision"
case .CFNetServiceErrorNotFound: return "CFNetServiceErrorNotFound"
case .CFNetServiceErrorInProgress: return "CFNetServiceErrorInProgress"
case .CFNetServiceErrorBadArgument: return "CFNetServiceErrorBadArgument"
case .CFNetServiceErrorCancel: return "CFNetServiceErrorCancel"
case .CFNetServiceErrorInvalid: return "CFNetServiceErrorInvalid"
case .CFNetServiceErrorTimeout: return "CFNetServiceErrorTimeout"
case .CFNetServiceErrorDNSServiceFailure: return "CFNetServiceErrorDNSServiceFailure"
default: return "Unknown"
}
}
class func register(server: WebServer) {
server.registerHandlerForMethod("GET", module: "errors", resource: "error.html", handler: { (request) -> GCDWebServerResponse! in
let urlString = request.query["url"] as? String
let url = (NSURL(string: urlString?.unescape() ?? "") ?? NSURL(string: ""))!
if let index = find(self.redirecting, url) {
self.redirecting.removeAtIndex(index)
let errCode = (request.query["code"] as! String).toInt()
let errDescription = request.query["description"] as! String
var errDomain = request.query["domain"] as! String
// If we don't have any other actions, we always add a try again button
let tryAgain = NSLocalizedString("Try again", tableName: "ErrorPages", comment: "Shown in error pages on a button that will try to load the page again")
var actions = "<button onclick='window.location.reload()'>\(tryAgain)</button>"
if errDomain == kCFErrorDomainCFNetwork as String {
if let code = CFNetworkErrors(rawValue: Int32(errCode!)) {
errDomain = self.cfErrorToName(code)
}
} else if errDomain == ErrorPageHelper.MozDomain {
if errCode == ErrorPageHelper.MozErrorDownloadsNotEnabled {
// Overwrite the normal try-again action.
let downloadInSafari = NSLocalizedString("Open in Safari", tableName: "ErrorPages", comment: "Shown in error pages for files that can't be shown and need to be downloaded.")
actions = "<button onclick='webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"openInSafari\"})'>\(downloadInSafari)</a>"
}
errDomain = ""
}
let asset = NSBundle.mainBundle().pathForResource("NetError", ofType: "html")
let response = GCDWebServerDataResponse(HTMLTemplate: asset, variables: [
"error_code": "\(errCode ?? -1)",
"error_title": errDescription ?? "",
"long_description": nil ?? "",
"short_description": errDomain,
"actions": actions
])
response.setValue("no cache", forAdditionalHeader: "Pragma")
response.setValue("no-cache,must-revalidate", forAdditionalHeader: "Cache-Control")
response.setValue(NSDate().description, forAdditionalHeader: "Expires")
return response
} else {
return GCDWebServerDataResponse(redirect: url, permanent: false)
}
})
server.registerHandlerForMethod("GET", module: "errors", resource: "NetError.css", handler: { (request) -> GCDWebServerResponse! in
let path = NSBundle(forClass: self).pathForResource("NetError", ofType: "css")!
let data = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)! as String
return GCDWebServerDataResponse(data: NSData(contentsOfFile: path), contentType: "text/css")
})
}
func showPage(error: NSError, forUrl url: NSURL, inWebView webView: WKWebView) {
// Don't show error pages for error pages.
if ErrorPageHelper.isErrorPageURL(url) {
let previousUrl = ErrorPageHelper.decodeURL(url)
if let index = find(ErrorPageHelper.redirecting, previousUrl) {
ErrorPageHelper.redirecting.removeAtIndex(index)
}
return
}
// Add this page to the redirecting list. This will cause the server to actually show the error page
// (instead of redirecting to the original URL).
ErrorPageHelper.redirecting.append(url)
let errorUrl = "\(WebServer.sharedInstance.base)/errors/error.html?url=\(url.absoluteString?.escape() ?? String())&code=\(error.code)&domain=\(error.domain)&description=\(error.localizedDescription.escape())"
let request = NSURLRequest(URL: errorUrl.asURL!)
webView.loadRequest(request)
}
class func isErrorPageURL(url: NSURL) -> Bool {
if let scheme = url.scheme, host = url.host, path = url.path {
return scheme == "http" && host == "localhost" && path == "/errors/error.html"
}
return false
}
class func decodeURL(url: NSURL) -> NSURL {
let query = url.getQuery()
let queryUrl = query["url"]
return NSURL(string: query["url"]?.unescape() ?? "")!
}
}
extension ErrorPageHelper: BrowserHelper {
static func name() -> String {
return "ErrorPageHelper"
}
func scriptMessageHandlerName() -> String? {
return "errorPageHelperMessageManager"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let url = message.frameInfo.request.URL {
if message.frameInfo.mainFrame && ErrorPageHelper.isErrorPageURL(url) {
var res = message.body as! [String: String]
let type = res["type"]
if type == "openInSafari" {
UIApplication.sharedApplication().openURL(ErrorPageHelper.decodeURL(url))
}
}
}
}
}
| mpl-2.0 | 12499ca87ff958da77f25f3fa307de69 | 60.658879 | 216 | 0.717317 | 5.777145 | false | false | false | false |
volodg/iAsync.async | Pods/iAsync.async/Lib/JAsyncBlockDefinitions.swift | 2 | 1417 | //
// JAsyncBlockDefinitions.swift
// JAsync
//
// Created by Vladimir Gorbenko on 11.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
public typealias JAsyncProgressCallback = (progressInfo: AnyObject) -> ()
public typealias JAsyncChangeStateCallback = (state: JAsyncState) -> ()
public typealias JAsyncHandler = (task: JAsyncHandlerTask) -> ()
public enum JAsyncTypes<T> {
public typealias ResultType = T
public typealias JDidFinishAsyncCallback = (result: JResult<T>) -> ()
public typealias JAsync = (
progressCallback: JAsyncProgressCallback?,
stateCallback : JAsyncChangeStateCallback?,
finishCallback : JDidFinishAsyncCallback?) -> JAsyncHandler
//Synchronous block which can take a lot of time
public typealias JSyncOperation = () -> JResult<T>
//This block should call progress_callback_ block only from own thread
public typealias JSyncOperationWithProgress = (progressCallback: JAsyncProgressCallback?) -> JResult<T>
}
public enum JAsyncTypes2<T1, T2> {
public typealias BinderType = T1
public typealias ResultType = T2
public typealias JAsyncBinder = (T1) -> JAsyncTypes<T2>.JAsync
public typealias JDidFinishAsyncHook = (
result : JResult<T1>,
finishCallback: JAsyncTypes<T2>.JDidFinishAsyncCallback?) -> ()
}
| mit | d7723baa9b85df63408b0849884aee83 | 29.804348 | 107 | 0.706422 | 4.442006 | false | false | false | false |
tkremenek/swift | stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift | 4 | 15097 | //===--- Subprocess.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
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
import WinSDK
#endif
#if !os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
internal func _signalToString(_ signal: Int) -> String {
switch CInt(signal) {
case SIGILL: return "SIGILL"
case SIGABRT: return "SIGABRT"
case SIGFPE: return "SIGFPE"
case SIGSEGV: return "SIGSEGV"
#if !os(Windows)
case SIGTRAP: return "SIGTRAP"
case SIGBUS: return "SIGBUS"
case SIGSYS: return "SIGSYS"
#endif
default: return "SIG???? (\(signal))"
}
}
#endif
public enum ProcessTerminationStatus : CustomStringConvertible {
case exit(Int)
case signal(Int)
public var description: String {
switch self {
case .exit(let status):
return "Exit(\(status))"
case .signal(let signal):
#if os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
fatalError("Signals are not supported on WebAssembly/WASI")
#else
return "Signal(\(_signalToString(signal)))"
#endif
}
}
}
#if os(Windows)
public func spawnChild(_ args: [String])
-> (process: HANDLE, stdin: HANDLE, stdout: HANDLE, stderr: HANDLE) {
var _stdin: (read: HANDLE?, write: HANDLE?)
var _stdout: (read: HANDLE?, write: HANDLE?)
var _stderr: (read: HANDLE?, write: HANDLE?)
var saAttributes: SECURITY_ATTRIBUTES = SECURITY_ATTRIBUTES()
saAttributes.nLength = DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size)
saAttributes.bInheritHandle = true
saAttributes.lpSecurityDescriptor = nil
if !CreatePipe(&_stdin.read, &_stdin.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stdin.write, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
if !CreatePipe(&_stdout.read, &_stdout.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stdout.read, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
if !CreatePipe(&_stderr.read, &_stderr.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stderr.read, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
var siStartupInfo: STARTUPINFOW = STARTUPINFOW()
siStartupInfo.cb = DWORD(MemoryLayout<STARTUPINFOW>.size)
siStartupInfo.hStdError = _stderr.write
siStartupInfo.hStdOutput = _stdout.write
siStartupInfo.hStdInput = _stdin.read
siStartupInfo.dwFlags |= STARTF_USESTDHANDLES
var piProcessInfo: PROCESS_INFORMATION = PROCESS_INFORMATION()
// TODO(compnerd): properly quote the command line being invoked here. See
// https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
// for more details on how to properly quote the command line for Windows.
let command: String =
([CommandLine.arguments[0]] + args).joined(separator: " ")
command.withCString(encodedAs: UTF16.self) { cString in
if !CreateProcessW(nil, UnsafeMutablePointer<WCHAR>(mutating: cString),
nil, nil, true, 0, nil, nil,
&siStartupInfo, &piProcessInfo) {
let dwError: DWORD = GetLastError()
fatalError("CreateProcessW() failed \(dwError)")
}
}
if !CloseHandle(_stdin.read) {
fatalError("CloseHandle() failed")
}
if !CloseHandle(_stdout.write) {
fatalError("CloseHandle() failed")
}
if !CloseHandle(_stderr.write) {
fatalError("CloseHandle() failed")
}
// CloseHandle(piProcessInfo.hProcess)
CloseHandle(piProcessInfo.hThread)
return (piProcessInfo.hProcess,
_stdin.write ?? INVALID_HANDLE_VALUE,
_stdout.read ?? INVALID_HANDLE_VALUE,
_stderr.read ?? INVALID_HANDLE_VALUE)
}
public func waitProcess(_ process: HANDLE) -> ProcessTerminationStatus {
let result = WaitForSingleObject(process, INFINITE)
if result != WAIT_OBJECT_0 {
fatalError("WaitForSingleObject() failed")
}
var status: DWORD = 0
if !GetExitCodeProcess(process, &status) {
fatalError("GetExitCodeProcess() failed")
}
if status & DWORD(0x80000000) == DWORD(0x80000000) {
return .signal(Int(status))
}
return .exit(Int(status))
}
#elseif os(WASI)
// WASI doesn't support child processes
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
fatalError("\(#function) is not supported on WebAssembly/WASI")
}
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
fatalError("\(#function) is not supported on WebAssembly/WASI")
}
#else
// posix_spawn is not available on Android.
// posix_spawn is not available on Haiku.
#if !os(Android) && !os(Haiku)
// posix_spawn isn't available in the public watchOS SDK, we sneak by the
// unavailable attribute declaration here of the APIs that we need.
// FIXME: Come up with a better way to deal with APIs that are pointers on some
// platforms but not others.
#if os(Linux)
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
@_silgen_name("_stdlib_posix_spawn_file_actions_init")
internal func _stdlib_posix_spawn_file_actions_init(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_destroy")
internal func _stdlib_posix_spawn_file_actions_destroy(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_addclose")
internal func _stdlib_posix_spawn_file_actions_addclose(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_adddup2")
internal func _stdlib_posix_spawn_file_actions_adddup2(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt,
_ newfiledes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn")
internal func _stdlib_posix_spawn(
_ pid: UnsafeMutablePointer<pid_t>?,
_ file: UnsafePointer<Int8>,
_ file_actions: UnsafePointer<_stdlib_posix_spawn_file_actions_t>?,
_ attrp: UnsafePointer<posix_spawnattr_t>?,
_ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>,
_ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt
#endif
/// Calls POSIX `pipe()`.
func posixPipe() -> (readFD: CInt, writeFD: CInt) {
var fds: [CInt] = [ -1, -1 ]
if pipe(&fds) != 0 {
preconditionFailure("pipe() failed")
}
return (fds[0], fds[1])
}
/// Start the same executable as a child process, redirecting its stdout and
/// stderr.
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
// The stdout, stdin, and stderr from the child process will be redirected
// to these pipes.
let childStdout = posixPipe()
let childStdin = posixPipe()
let childStderr = posixPipe()
#if os(Android) || os(Haiku)
// posix_spawn isn't available on Android. Instead, we fork and exec.
// To correctly communicate the exit status of the child process to this
// (parent) process, we'll use this pipe.
let childToParentPipe = posixPipe()
let pid = fork()
precondition(pid >= 0, "fork() failed")
if pid == 0 {
// pid of 0 means we are now in the child process.
// Capture the output before executing the program.
close(childStdout.readFD)
close(childStdin.writeFD)
close(childStderr.readFD)
close(childToParentPipe.readFD)
dup2(childStdout.writeFD, STDOUT_FILENO)
dup2(childStdin.readFD, STDIN_FILENO)
dup2(childStderr.writeFD, STDERR_FILENO)
// Set the "close on exec" flag on the parent write pipe. This will
// close the pipe if the execve() below successfully executes a child
// process.
let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC)
let closeErrno = errno
precondition(
closeResult == 0,
"Could not set the close behavior of the child-to-parent pipe; " +
"errno: \(closeErrno)")
// Start the executable. If execve() does not encounter an error, the
// code after this block will never be executed, and the parent write pipe
// will be closed.
withArrayOfCStrings([CommandLine.arguments[0]] + args) {
execve(CommandLine.arguments[0], $0, environ)
}
// If execve() encountered an error, we write the errno encountered to the
// parent write pipe.
let errnoSize = MemoryLayout.size(ofValue: errno)
var execveErrno = errno
let writtenBytes = withUnsafePointer(to: &execveErrno) {
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)
}
let writeErrno = errno
if writtenBytes > 0 && writtenBytes < errnoSize {
// We were able to write some of our error, but not all of it.
// FIXME: Retry in this case.
preconditionFailure("Unable to write entire error to child-to-parent " +
"pipe.")
} else if writtenBytes == 0 {
preconditionFailure("Unable to write error to child-to-parent pipe.")
} else if writtenBytes < 0 {
preconditionFailure("An error occurred when writing error to " +
"child-to-parent pipe; errno: \(writeErrno)")
}
// Close the pipe when we're done writing the error.
close(childToParentPipe.writeFD)
} else {
close(childToParentPipe.writeFD)
// Figure out if the child’s call to execve was successful or not.
var readfds = _stdlib_fd_set()
readfds.set(childToParentPipe.readFD)
var writefds = _stdlib_fd_set()
var errorfds = _stdlib_fd_set()
errorfds.set(childToParentPipe.readFD)
var ret: CInt
repeat {
ret = _stdlib_select(&readfds, &writefds, &errorfds, nil)
} while ret == -1 && errno == EINTR
if ret <= 0 {
fatalError("select() returned an error: \(errno)")
}
if readfds.isset(childToParentPipe.readFD) || errorfds.isset(childToParentPipe.readFD) {
var childErrno: CInt = 0
let readResult: ssize_t = withUnsafeMutablePointer(to: &childErrno) {
return read(childToParentPipe.readFD, $0, MemoryLayout.size(ofValue: $0.pointee))
}
if readResult == 0 {
// We read an EOF indicating that the child's call to execve was successful.
} else if readResult < 0 {
fatalError("read() returned error: \(errno)")
} else {
// We read an error from the child.
print(String(cString: strerror(childErrno)))
preconditionFailure("execve() failed")
}
}
close(childToParentPipe.readFD)
}
#else
var fileActions = _make_posix_spawn_file_actions_t()
if _stdlib_posix_spawn_file_actions_init(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_init() failed")
}
// Close the write end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdin.writeFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdin.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdin.readFD, STDIN_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdout.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdout.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStderr.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stderr.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStderr.writeFD, STDERR_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
var pid: pid_t = -1
var childArgs = args
childArgs.insert(CommandLine.arguments[0], at: 0)
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let invocation = String(validatingUTF8: interpreter!) {
childArgs.insert(invocation, at: 0)
}
}
let spawnResult = withArrayOfCStrings(childArgs) {
_stdlib_posix_spawn(
&pid, childArgs[0], &fileActions, nil, $0, environ)
}
if spawnResult != 0 {
print(String(cString: strerror(spawnResult)))
preconditionFailure("_stdlib_posix_spawn() failed")
}
if _stdlib_posix_spawn_file_actions_destroy(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_destroy() failed")
}
#endif
// Close the read end of the pipe on the parent side.
if close(childStdin.readFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStdout.writeFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStderr.writeFD) != 0 {
preconditionFailure("close() failed")
}
return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD)
}
#if !os(Android) && !os(Haiku)
#if os(Linux)
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return posix_spawn_file_actions_t()
}
#else
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return nil
}
#endif
#endif
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
var status: CInt = 0
#if os(Cygwin)
withUnsafeMutablePointer(to: &status) {
statusPtr in
let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr)
while waitpid(pid, statusPtrWrapper, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
}
#else
while waitpid(pid, &status, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
#endif
if WIFEXITED(status) {
return .exit(Int(WEXITSTATUS(status)))
}
if WIFSIGNALED(status) {
return .signal(Int(WTERMSIG(status)))
}
preconditionFailure("did not understand what happened to child process")
}
// !os(Windows)
#endif
| apache-2.0 | 91cd25d8057b67d9e9afc9d1cdcc7c80 | 32.694196 | 131 | 0.684598 | 3.851748 | false | false | false | false |
marty-suzuki/HoverConversion | HoverConversion/HCNavigationView.swift | 1 | 4473 | //
// HCNavigationView.swift
// HoverConversion
//
// Created by Taiki Suzuki on 2016/07/18.
// Copyright © 2016年 marty-suzuki. All rights reserved.
//
import UIKit
import MisterFusion
public protocol HCNavigationViewDelegate: class {
func navigationView(_ navigationView: HCNavigationView, didTapLeftButton button: UIButton)
func navigationView(_ navigationView: HCNavigationView, didTapRightButton button: UIButton)
}
open class HCNavigationView: UIView {
public struct ButtonPosition: OptionSet {
static let right = ButtonPosition(rawValue: 1 << 0)
static let left = ButtonPosition(rawValue: 1 << 1)
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
open static let height: CGFloat = 64
open var leftButton: UIButton?
open let titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 16)
return label
}()
open var rightButton: UIButton?
weak var delegate: HCNavigationViewDelegate?
public convenience init() {
self.init(buttonPosition: [])
}
public init(buttonPosition: ButtonPosition) {
super.init(frame: .zero)
if buttonPosition.contains(.left) {
let leftButton = UIButton(type: .custom)
addLayoutSubview(leftButton, andConstraints:
leftButton.left,
leftButton.bottom,
leftButton.width |==| leftButton.height,
leftButton.height |==| 44
)
leftButton.setTitle("‹", for: UIControlState())
leftButton.titleLabel?.font = .systemFont(ofSize: 40)
leftButton.addTarget(self, action: #selector(HCNavigationView.didTouchDown(_:)), for: .touchDown)
leftButton.addTarget(self, action: #selector(HCNavigationView.didTouchDragExit(_:)), for: .touchDragExit)
leftButton.addTarget(self, action: #selector(HCNavigationView.didTouchDragEnter(_:)), for: .touchDragEnter)
leftButton.addTarget(self, action: #selector(HCNavigationView.didTouchUpInside(_:)), for: .touchUpInside)
self.leftButton = leftButton
}
if buttonPosition.contains(.right) {
let rightButton = UIButton(type: .custom)
addLayoutSubview(rightButton, andConstraints:
rightButton.right,
rightButton.bottom,
rightButton.width |==| rightButton.height,
rightButton.height |==| 44
)
rightButton.addTarget(self, action: #selector(HCNavigationView.didTouchDown(_:)), for: .touchDown)
rightButton.addTarget(self, action: #selector(HCNavigationView.didTouchDragExit(_:)), for: .touchDragExit)
rightButton.addTarget(self, action: #selector(HCNavigationView.didTouchDragEnter(_:)), for: .touchDragEnter)
rightButton.addTarget(self, action: #selector(HCNavigationView.didTouchUpInside(_:)), for: .touchUpInside)
self.rightButton = rightButton
}
var constraints: [MisterFusion] = []
if let leftButton = leftButton {
constraints += [leftButton.right |==| titleLabel.left]
} else {
constraints += [titleLabel.left |+| 44]
}
if let rightButton = rightButton {
constraints += [rightButton.left |==| titleLabel.right]
} else {
constraints += [titleLabel.right |-| 44]
}
constraints += [
titleLabel.height |==| 44,
titleLabel.bottom
]
addLayoutSubview(titleLabel, andConstraints: constraints)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func didTouchUpInside(_ sender: UIButton) {
sender.alpha = 1
if sender == leftButton {
delegate?.navigationView(self, didTapLeftButton: sender)
} else if sender == rightButton {
delegate?.navigationView(self, didTapRightButton: sender)
}
}
func didTouchDown(_ sender: UIButton) {
sender.alpha = 0.5
}
func didTouchDragExit(_ sender: UIButton) {
sender.alpha = 0.5
}
func didTouchDragEnter(_ sender: UIButton) {
sender.alpha = 1
}
}
| mit | 2da85384bed05910c6268029ecbca308 | 35.92562 | 120 | 0.617502 | 5.207459 | false | false | false | false |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Text Fields/DarkBorderTextField.swift | 1 | 1035 |
import UIKit
public class DarkBorderTextField: UITextField, Configurable{
override public init(frame: CGRect) {
super.init(frame: frame)
config()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
config()
}
func config() {
self.backgroundColor = UIColor.appColor(color: .Light)
self.font = UIFont.appFont(font: .RubikRegular, pontSize: 15)
self.layer.cornerRadius = 5
self.layer.borderColor = UIColor.appColor(color: .Dark).cgColor
self.layer.borderWidth = 1
}
public override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x+8, y: bounds.origin.y, width: bounds.size.width-16, height: bounds.size.height)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x+8, y: bounds.origin.y, width: bounds.size.width-16, height: bounds.size.height)
}
}
| mit | 937b9c131a1034f986009c89b66f49ff | 29.441176 | 120 | 0.635749 | 4.042969 | false | true | false | false |
zisko/swift | stdlib/public/SDK/Foundation/Decimal.swift | 2 | 18793 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
extension Decimal {
public typealias RoundingMode = NSDecimalNumber.RoundingMode
public typealias CalculationError = NSDecimalNumber.CalculationError
public static let leastFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff))
public static let greatestFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff))
public static let leastNormalMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
public static let leastNonzeroMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
public static let pi = Decimal(_exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58))
public var exponent: Int {
get {
return Int(_exponent)
}
}
public var significand: Decimal {
get {
return Decimal(_exponent: 0, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa)
}
}
public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) {
self.init(_exponent: Int32(exponent) + significand._exponent, _length: significand._length, _isNegative: sign == .plus ? 0 : 1, _isCompact: significand._isCompact, _reserved: 0, _mantissa: significand._mantissa)
}
public init(signOf: Decimal, magnitudeOf magnitude: Decimal) {
self.init(_exponent: magnitude._exponent, _length: magnitude._length, _isNegative: signOf._isNegative, _isCompact: magnitude._isCompact, _reserved: 0, _mantissa: magnitude._mantissa)
}
public var sign: FloatingPointSign {
return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus
}
public static var radix: Int { return 10 }
public var ulp: Decimal {
if !self.isFinite { return Decimal.nan }
return Decimal(_exponent: _exponent, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") }
public mutating func negate() {
_isNegative = _isNegative == 0 ? 1 : 0
}
public func isEqual(to other: Decimal) -> Bool {
var lhs = self
var rhs = other
return NSDecimalCompare(&lhs, &rhs) == .orderedSame
}
public func isLess(than other: Decimal) -> Bool {
var lhs = self
var rhs = other
return NSDecimalCompare(&lhs, &rhs) == .orderedAscending
}
public func isLessThanOrEqualTo(_ other: Decimal) -> Bool {
var lhs = self
var rhs = other
let order = NSDecimalCompare(&lhs, &rhs)
return order == .orderedAscending || order == .orderedSame
}
public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool {
// Notes: Decimal does not have -0 or infinities to worry about
if self.isNaN {
return false
} else if self < other {
return true
} else if other < self {
return false
}
// fall through to == behavior
return true
}
public var isCanonical: Bool {
return true
}
public var nextUp: Decimal {
return self + Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public var nextDown: Decimal {
return self - Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public static func +(lhs: Decimal, rhs: Decimal) -> Decimal {
var res = Decimal()
var leftOp = lhs
var rightOp = rhs
NSDecimalAdd(&res, &leftOp, &rightOp, .plain)
return res
}
public static func -(lhs: Decimal, rhs: Decimal) -> Decimal {
var res = Decimal()
var leftOp = lhs
var rightOp = rhs
NSDecimalSubtract(&res, &leftOp, &rightOp, .plain)
return res
}
public static func /(lhs: Decimal, rhs: Decimal) -> Decimal {
var res = Decimal()
var leftOp = lhs
var rightOp = rhs
NSDecimalDivide(&res, &leftOp, &rightOp, .plain)
return res
}
public static func *(lhs: Decimal, rhs: Decimal) -> Decimal {
var res = Decimal()
var leftOp = lhs
var rightOp = rhs
NSDecimalMultiply(&res, &leftOp, &rightOp, .plain)
return res
}
}
public func pow(_ x: Decimal, _ y: Int) -> Decimal {
var res = Decimal()
var num = x
NSDecimalPower(&res, &num, y, .plain)
return res
}
extension Decimal : Hashable, Comparable {
internal var doubleValue : Double {
var d = 0.0
if _length == 0 && _isNegative == 0 {
return Double.nan
}
d = d * 65536 + Double(_mantissa.7)
d = d * 65536 + Double(_mantissa.6)
d = d * 65536 + Double(_mantissa.5)
d = d * 65536 + Double(_mantissa.4)
d = d * 65536 + Double(_mantissa.3)
d = d * 65536 + Double(_mantissa.2)
d = d * 65536 + Double(_mantissa.1)
d = d * 65536 + Double(_mantissa.0)
if _exponent < 0 {
for _ in _exponent..<0 {
d /= 10.0
}
} else {
for _ in 0..<_exponent {
d *= 10.0
}
}
return _isNegative != 0 ? -d : d
}
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(doubleValue))
}
public static func ==(lhs: Decimal, rhs: Decimal) -> Bool {
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame
}
public static func <(lhs: Decimal, rhs: Decimal) -> Bool {
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending
}
}
extension Decimal : ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
extension Decimal : ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension Decimal : SignedNumeric {
public var magnitude: Decimal {
return Decimal(
_exponent: self._exponent, _length: self._length,
_isNegative: 0, _isCompact: self._isCompact,
_reserved: 0, _mantissa: self._mantissa)
}
// FIXME(integers): implement properly
public init?<T : BinaryInteger>(exactly source: T) {
fatalError()
}
public static func +=(_ lhs: inout Decimal, _ rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalAdd($0, $0, &rhs, .plain)
}
}
public static func -=(_ lhs: inout Decimal, _ rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalSubtract($0, $0, &rhs, .plain)
}
}
public static func *=(_ lhs: inout Decimal, _ rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalMultiply($0, $0, &rhs, .plain)
}
}
public static func /=(_ lhs: inout Decimal, _ rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalDivide($0, $0, &rhs, .plain)
}
}
}
extension Decimal {
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func add(_ other: Decimal) {
self += other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func subtract(_ other: Decimal) {
self -= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func multiply(by other: Decimal) {
self *= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func divide(by other: Decimal) {
self /= other
}
}
extension Decimal : Strideable {
public func distance(to other: Decimal) -> Decimal {
return self - other
}
public func advanced(by n: Decimal) -> Decimal {
return self + n
}
}
extension Decimal {
public init(_ value: UInt8) {
self.init(UInt64(value))
}
public init(_ value: Int8) {
self.init(Int64(value))
}
public init(_ value: UInt16) {
self.init(UInt64(value))
}
public init(_ value: Int16) {
self.init(Int64(value))
}
public init(_ value: UInt32) {
self.init(UInt64(value))
}
public init(_ value: Int32) {
self.init(Int64(value))
}
public init(_ value: Double) {
if value.isNaN {
self = Decimal.nan
} else if value == 0.0 {
self = Decimal(_exponent: 0, _length: 0, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
} else {
self.init() // zero-initialize everything
let negative = value < 0
var val = negative ? -1 * value : value
var exponent = 0
while val < Double(UInt64.max - 1) {
val *= 10.0
exponent -= 1
}
while Double(UInt64.max - 1) < val {
val /= 10.0
exponent += 1
}
var mantissa = UInt64(val)
var i = UInt32(0)
// this is a bit ugly but it is the closest approximation of the C initializer that can be expressed here.
while mantissa != 0 && i < 8 /* NSDecimalMaxSize */ {
switch i {
case 0:
_mantissa.0 = UInt16(mantissa & 0xffff)
case 1:
_mantissa.1 = UInt16(mantissa & 0xffff)
case 2:
_mantissa.2 = UInt16(mantissa & 0xffff)
case 3:
_mantissa.3 = UInt16(mantissa & 0xffff)
case 4:
_mantissa.4 = UInt16(mantissa & 0xffff)
case 5:
_mantissa.5 = UInt16(mantissa & 0xffff)
case 6:
_mantissa.6 = UInt16(mantissa & 0xffff)
case 7:
_mantissa.7 = UInt16(mantissa & 0xffff)
default:
fatalError("initialization overflow")
}
mantissa = mantissa >> 16
i += 1
}
_length = i
_isNegative = negative ? 1 : 0
_isCompact = 0
_exponent = Int32(exponent)
NSDecimalCompact(&self)
}
}
public init(_ value: UInt64) {
self.init(Double(value))
}
public init(_ value: Int64) {
self.init(Double(value))
}
public init(_ value: UInt) {
self.init(UInt64(value))
}
public init(_ value: Int) {
self.init(Int64(value))
}
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public static var infinity: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") }
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public static var signalingNaN: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") }
public var isSignalingNaN: Bool {
return false
}
public static var nan: Decimal {
return quietNaN
}
public static var quietNaN: Decimal {
return Decimal(_exponent: 0, _length: 0, _isNegative: 1, _isCompact: 0, _reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0))
}
/// The IEEE 754 "class" of this type.
public var floatingPointClass: FloatingPointClassification {
if _length == 0 && _isNegative == 1 {
return .quietNaN
} else if _length == 0 {
return .positiveZero
}
// NSDecimal does not really represent normal and subnormal in the same manner as the IEEE standard, for now we can probably claim normal for any nonzero, nonnan values
if _isNegative == 1 {
return .negativeNormal
} else {
return .positiveNormal
}
}
/// `true` iff `self` is negative.
public var isSignMinus: Bool { return _isNegative != 0 }
/// `true` iff `self` is normal (not zero, subnormal, infinity, or
/// NaN).
public var isNormal: Bool { return !isZero && !isInfinite && !isNaN }
/// `true` iff `self` is zero, subnormal, or normal (not infinity
/// or NaN).
public var isFinite: Bool { return !isNaN }
/// `true` iff `self` is +0.0 or -0.0.
public var isZero: Bool { return _length == 0 && _isNegative == 0 }
/// `true` iff `self` is subnormal.
public var isSubnormal: Bool { return false }
/// `true` iff `self` is infinity.
public var isInfinite: Bool { return false }
/// `true` iff `self` is NaN.
public var isNaN: Bool { return _length == 0 && _isNegative == 1 }
/// `true` iff `self` is a signaling NaN.
public var isSignaling: Bool { return false }
}
extension Decimal : CustomStringConvertible {
public init?(string: String, locale: Locale? = nil) {
let scan = Scanner(string: string)
var theDecimal = Decimal()
scan.locale = locale
if !scan.scanDecimal(&theDecimal) {
return nil
}
self = theDecimal
}
public var description: String {
var val = self
return NSDecimalString(&val, nil)
}
}
extension Decimal : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDecimalNumber {
return NSDecimalNumber(decimal: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSDecimalNumber, result: inout Decimal?) -> Bool {
result = input.decimalValue
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDecimalNumber?) -> Decimal {
guard let src = source else { return Decimal(_exponent: 0, _length: 0, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0)) }
return src.decimalValue
}
}
extension Decimal : Codable {
private enum CodingKeys : Int, CodingKey {
case exponent
case length
case isNegative
case isCompact
case mantissa
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let exponent = try container.decode(CInt.self, forKey: .exponent)
let length = try container.decode(CUnsignedInt.self, forKey: .length)
let isNegative = try container.decode(Bool.self, forKey: .isNegative)
let isCompact = try container.decode(Bool.self, forKey: .isCompact)
var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa)
var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort,
CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0)
mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self)
self = Decimal(_exponent: exponent,
_length: length,
_isNegative: CUnsignedInt(isNegative ? 1 : 0),
_isCompact: CUnsignedInt(isCompact ? 1 : 0),
_reserved: 0,
_mantissa: mantissa)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_exponent, forKey: .exponent)
try container.encode(_length, forKey: .length)
try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative)
try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact)
var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa)
try mantissaContainer.encode(_mantissa.0)
try mantissaContainer.encode(_mantissa.1)
try mantissaContainer.encode(_mantissa.2)
try mantissaContainer.encode(_mantissa.3)
try mantissaContainer.encode(_mantissa.4)
try mantissaContainer.encode(_mantissa.5)
try mantissaContainer.encode(_mantissa.6)
try mantissaContainer.encode(_mantissa.7)
}
}
| apache-2.0 | f30a926f4b654b56cb7489212864fa62 | 34.864504 | 219 | 0.594317 | 4.327193 | false | false | false | false |
zisko/swift | test/SILGen/property_abstraction.swift | 1 | 6460 | // RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
struct Int {
mutating func foo() {}
}
struct Foo<T, U> {
var f: (T) -> U
var g: T
}
// CHECK-LABEL: sil hidden @$S20property_abstraction4getF{{[_0-9a-zA-Z]*}}Foo{{.*}}F : $@convention(thin) (@owned Foo<Int, Int>) -> @owned @callee_guaranteed (Int) -> Int {
// CHECK: bb0([[X_ORIG:%.*]] : @owned $Foo<Int, Int>):
// CHECK: [[BORROWED_X_ORIG:%.*]] = begin_borrow [[X_ORIG]] : $Foo<Int, Int>
// CHECK: [[F_ORIG:%.*]] = struct_extract [[BORROWED_X_ORIG]] : $Foo<Int, Int>, #Foo.f
// CHECK: [[F_ORIG_COPY:%.*]] = copy_value [[F_ORIG]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_ORIG_COPY]])
// CHECK: end_borrow [[BORROWED_X_ORIG]] from [[X_ORIG]]
// CHECK: destroy_value [[X_ORIG]]
// CHECK: return [[F_SUBST]]
// CHECK: } // end sil function '$S20property_abstraction4getF{{[_0-9a-zA-Z]*}}F'
func getF(_ x: Foo<Int, Int>) -> (Int) -> Int {
return x.f
}
// CHECK-LABEL: sil hidden @$S20property_abstraction4setF{{[_0-9a-zA-Z]*}}F
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_ORIG:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]({{%.*}})
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func setF(_ x: inout Foo<Int, Int>, f: @escaping (Int) -> Int) {
x.f = f
}
func inOutFunc(_ f: inout ((Int) -> Int)) { }
// CHECK-LABEL: sil hidden @$S20property_abstraction6inOutF{{[_0-9a-zA-Z]*}}F :
// CHECK: bb0([[ARG:%.*]] : @owned $Foo<Int, Int>):
// CHECK: [[XBOX:%.*]] = alloc_box ${ var Foo<Int, Int> }, var, name "x"
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] : ${ var Foo<Int, Int> }, 0
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[XBOX_PB]] : $*Foo<Int, Int>
// CHECK: [[F_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*Foo<Int, Int>, #Foo.f
// CHECK: [[F_SUBST_MAT:%.*]] = alloc_stack
// CHECK: [[F_ORIG:%.*]] = load [copy] [[F_ADDR]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_SUBST_IN:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: store [[F_SUBST_IN]] to [init] [[F_SUBST_MAT]]
// CHECK: [[INOUTFUNC:%.*]] = function_ref @$S20property_abstraction9inOutFunc{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[INOUTFUNC]]([[F_SUBST_MAT]])
// CHECK: [[F_SUBST_OUT:%.*]] = load [take] [[F_SUBST_MAT]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_ORIG:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_SUBST_OUT]])
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
// CHECK: destroy_value [[XBOX]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '$S20property_abstraction6inOutF{{[_0-9a-zA-Z]*}}F'
func inOutF(_ x: Foo<Int, Int>) {
var x = x
inOutFunc(&x.f)
}
// Don't produce a writeback for generic lvalues when there's no real
// abstraction difference. <rdar://problem/16530674>
// CHECK-LABEL: sil hidden @$S20property_abstraction23noAbstractionDifference{{[_0-9a-zA-Z]*}}F
func noAbstractionDifference(_ x: Foo<Int, Int>) {
var x = x
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}}, #Foo.g
// CHECK: apply {{%.*}}([[ADDR]])
x.g.foo()
}
protocol P {}
struct AddressOnlyLet<T> {
let f: (T) -> T
let makeAddressOnly: P
}
// CHECK-LABEL: sil hidden @$S20property_abstraction34getAddressOnlyReabstractedProperty{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in AddressOnlyLet<Int>) -> @owned @callee_guaranteed (Int) -> Int
// CHECK: bb0([[ARG:%.*]] : @trivial $*AddressOnlyLet<Int>):
// CHECK: [[CLOSURE_ADDR:%.*]] = struct_element_addr {{%.*}} : $*AddressOnlyLet<Int>, #AddressOnlyLet.f
// CHECK: [[CLOSURE_ORIG:%.*]] = load [copy] [[CLOSURE_ADDR]]
// CHECK: [[REABSTRACT:%.*]] = function_ref
// CHECK: [[CLOSURE_SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[CLOSURE_ORIG]])
// CHECK: destroy_addr [[ARG]]
// CHECK: return [[CLOSURE_SUBST]]
// CHECK: } // end sil function '$S20property_abstraction34getAddressOnlyReabstractedProperty{{[_0-9a-zA-Z]*}}F'
func getAddressOnlyReabstractedProperty(_ x: AddressOnlyLet<Int>) -> (Int) -> Int {
return x.f
}
enum Bar<T, U> {
case F((T) -> U)
}
func getF(_ x: Bar<Int, Int>) -> (Int) -> Int {
switch x {
case .F(var f):
return f
}
}
func makeF(_ f: @escaping (Int) -> Int) -> Bar<Int, Int> {
return Bar.F(f)
}
struct ArrayLike<T> {
subscript(x: ()) -> T { get {} set {} }
}
typealias Test20341012 = (title: (), action: () -> ())
struct T20341012 {
private var options: ArrayLike<Test20341012> { get {} set {} }
// CHECK-LABEL: sil hidden @$S20property_abstraction9T20341012V1t{{[_0-9a-zA-Z]*}}F
// CHECK: [[TMP1:%.*]] = alloc_stack $(title: (), action: @callee_guaranteed (@in ()) -> @out ())
// CHECK: apply {{.*}}<(title: (), action: () -> ())>([[TMP1]],
mutating func t() {
_ = self.options[].title
}
}
class MyClass {}
// When simply assigning to a property, reabstract the r-value and assign
// to the base instead of materializing and then assigning.
protocol Factory {
associatedtype Product
var builder : () -> Product { get set }
}
func setBuilder<F: Factory where F.Product == MyClass>(_ factory: inout F) {
factory.builder = { return MyClass() }
}
// CHECK: sil hidden @$S20property_abstraction10setBuilder{{[_0-9a-zA-Z]*}}F : $@convention(thin) <F where F : Factory, F.Product == MyClass> (@inout F) -> ()
// CHECK: bb0(%0 : @trivial $*F):
// CHECK: [[F0:%.*]] = function_ref @$S20property_abstraction10setBuilder{{[_0-9a-zA-Z]*}} : $@convention(thin) () -> @owned MyClass
// CHECK: [[F1:%.*]] = thin_to_thick_function [[F0]]
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F2:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[F1]])
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*F
// CHECK: [[SETTER:%.*]] = witness_method $F, #Factory.builder!setter.1
// CHECK: apply [[SETTER]]<F>([[F2]], [[WRITE]])
| apache-2.0 | f5feafedbce74bec6840529f5c4bdf72 | 42.355705 | 195 | 0.579257 | 3.123791 | false | false | false | false |
relayrides/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/TakeoverNotification.swift | 1 | 2826 | //
// TakeoverNotification.swift
// Mixpanel
//
// Created by Yarden Eitan on 1/24/17.
// Copyright © 2017 Mixpanel. All rights reserved.
//
import Foundation
class TakeoverNotification: InAppNotification {
let buttons: [InAppButton]
let closeButtonColor: UInt
var title: String? = nil
let titleColor: UInt
var shouldFadeImage: Bool = false
override init?(JSONObject: [String: Any]?) {
guard let object = JSONObject else {
Logger.error(message: "notification json object should not be nil")
return nil
}
guard let unparsedButtons = object["buttons"] as? [[String: Any]] else {
Logger.error(message: "invalid notification buttons list")
return nil
}
var parsedButtons = [InAppButton]()
for unparsedButton in unparsedButtons {
guard let button = InAppButton(JSONObject: unparsedButton) else {
Logger.error(message: "invalid notification button")
return nil
}
parsedButtons.append(button)
}
guard let closeButtonColor = object["close_color"] as? UInt else {
Logger.error(message: "invalid notification close button color")
return nil
}
if let title = object["title"] as? String {
self.title = title
}
guard let titleColor = object["title_color"] as? UInt else {
Logger.error(message: "invalid notification title color")
return nil
}
self.buttons = parsedButtons
self.closeButtonColor = closeButtonColor
self.titleColor = titleColor
super.init(JSONObject: JSONObject)
guard let shouldFadeImage = extras["image_fade"] as? Bool else {
Logger.error(message: "invalid notification fade image boolean")
return nil
}
self.shouldFadeImage = shouldFadeImage
imageURL = URL(string: imageURL.absoluteString.appendSuffixBeforeExtension(suffix: "@2x"))!
}
}
extension String {
func appendSuffixBeforeExtension(suffix: String) -> String {
var newString = suffix
do {
let regex = try NSRegularExpression(pattern: "(\\.\\w+$)", options: [])
newString = regex.stringByReplacingMatches(in: self,
options: [],
range: NSRange(location: 0,
length: self.characters.count),
withTemplate: "\(suffix)$1")
} catch {
Logger.error(message: "cannot add suffix to URL string")
}
return newString
}
}
| apache-2.0 | 44094342e2227cd788b26e1ecd773bf9 | 32.235294 | 101 | 0.55823 | 5.202578 | false | false | false | false |
jterhorst/TacoDemoiOS | Taco.swift | 1 | 1285 | //
// Taco.swift
// TacoDemoIOS
//
// Created by Jason Terhorst on 3/22/16.
// Copyright © 2016 Jason Terhorst. All rights reserved.
//
import Foundation
import CoreData
class Taco: NSManagedObject {
func updateWithDictionary(json: Dictionary<String, AnyObject>) {
if let newName = json["name"] as? String {
self.name = newName
}
if let newMeat = json["meat"] as? String {
self.meat = newMeat
}
if let newLayers = json["layers"] as? NSNumber {
self.layers = newLayers
}
if let newCalories = json["calories"] as? NSNumber {
self.calories = newCalories
}
if let newCheese = json["has_cheese"] as? NSNumber {
self.hasCheese = newCheese
}
if let newLettuce = json["has_lettuce"] as? NSNumber {
self.hasLettuce = newLettuce
}
if let newDetails = json["details"] as? String {
self.details = newDetails
}
}
func dictionaryRepresentation() -> Dictionary<String, AnyObject> {
var dict = Dictionary<String, AnyObject>()
dict["name"] = self.name as AnyObject?
dict["meat"] = self.meat as AnyObject?
dict["layers"] = self.layers
dict["calories"] = self.calories
dict["has_cheese"] = self.hasCheese
dict["has_lettuce"] = self.hasLettuce
dict["details"] = self.details as AnyObject?
return dict
}
}
| mit | d04cfdbfc7035ea05355e9f9ddbd71da | 24.176471 | 67 | 0.666667 | 3.335065 | false | false | false | false |
ziaukhan/Swift-Big-Nerd-Ranch-Guide | chapter 1/Quiz with Storyboard/Chap1/ViewController.swift | 1 | 1563 | //
// ViewController.swift
// Chap1
//
// Created by PanaCloud on 7/17/14.
// Copyright (c) 2014 PanaCloud. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var QuesLbl: UILabel?
@IBOutlet var AnsLbl: UILabel?
@IBOutlet var AnsBtn: UIButton?
@IBOutlet var QuesBtn: UIButton?
var Question:[String] = ["From what is cognac made?", "What is 7+7", "What is the capital of Vermont?"]
var Answer:[String] = ["Grapes", "14", "Montpelier"]
//Initialization for loop
var i:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Setting 1st Question to Label of Question on Start of App
ShowQuesBtnAction("AnyObject")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ShowQuesBtnAction(sender: AnyObject) {
//All Questions are done
if(i == Question.count){
QuesBtn!.enabled = false
AnsBtn!.enabled = false
}
else{
QuesLbl!.text = Question[i]
AnsLbl!.text = "???"
QuesBtn!.enabled = false
AnsBtn!.enabled = true
}
}
@IBAction func ShowAnsBtnAction(sender: AnyObject) {
AnsLbl!.text = Answer[i]
QuesBtn!.enabled = true
AnsBtn!.enabled = false
i++
}
}
| apache-2.0 | 9da8d45e71fceae259d643786dac8218 | 25.05 | 107 | 0.588612 | 4.293956 | false | false | false | false |
mamouneyya/TheSkillsProof | Pods/SwiftyUserDefaults/Sources/SwiftyUserDefaults.swift | 1 | 15743 | //
// SwiftyUserDefaults
//
// Copyright (c) 2015-2016 Radosław Pietruszewski
//
// 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 extension NSUserDefaults {
class Proxy {
private let defaults: NSUserDefaults
private let key: String
private init(_ defaults: NSUserDefaults, _ key: String) {
self.defaults = defaults
self.key = key
}
// MARK: Getters
public var object: NSObject? {
return defaults.objectForKey(key) as? NSObject
}
public var string: String? {
return defaults.stringForKey(key)
}
public var array: NSArray? {
return defaults.arrayForKey(key)
}
public var dictionary: NSDictionary? {
return defaults.dictionaryForKey(key)
}
public var data: NSData? {
return defaults.dataForKey(key)
}
public var date: NSDate? {
return object as? NSDate
}
public var number: NSNumber? {
return defaults.numberForKey(key)
}
public var int: Int? {
return number?.integerValue
}
public var double: Double? {
return number?.doubleValue
}
public var bool: Bool? {
return number?.boolValue
}
// MARK: Non-Optional Getters
public var stringValue: String {
return string ?? ""
}
public var arrayValue: NSArray {
return array ?? []
}
public var dictionaryValue: NSDictionary {
return dictionary ?? NSDictionary()
}
public var dataValue: NSData {
return data ?? NSData()
}
public var numberValue: NSNumber {
return number ?? 0
}
public var intValue: Int {
return int ?? 0
}
public var doubleValue: Double {
return double ?? 0
}
public var boolValue: Bool {
return bool ?? false
}
}
/// `NSNumber` representation of a user default
func numberForKey(key: String) -> NSNumber? {
return objectForKey(key) as? NSNumber
}
/// Returns getter proxy for `key`
public subscript(key: String) -> Proxy {
return Proxy(self, key)
}
/// Sets value for `key`
public subscript(key: String) -> Any? {
get {
// return untyped Proxy
// (make sure we don't fall into infinite loop)
let proxy: Proxy = self[key]
return proxy
}
set {
switch newValue {
case let v as Int: setInteger(v, forKey: key)
case let v as Double: setDouble(v, forKey: key)
case let v as Bool: setBool(v, forKey: key)
case let v as NSURL: setURL(v, forKey: key)
case let v as NSObject: setObject(v, forKey: key)
case nil: removeObjectForKey(key)
default: assertionFailure("Invalid value type")
}
}
}
/// Returns `true` if `key` exists
public func hasKey(key: String) -> Bool {
return objectForKey(key) != nil
}
/// Removes value for `key`
public func remove(key: String) {
removeObjectForKey(key)
}
/// Removes all keys and values from user defaults
/// Use with caution!
/// - Note: This method only removes keys on the receiver `NSUserDefaults` object.
/// System-defined keys will still be present afterwards.
public func removeAll() {
for (key, _) in dictionaryRepresentation() {
removeObjectForKey(key)
}
}
}
/// Global shortcut for NSUserDefaults.standardUserDefaults()
public let Defaults = NSUserDefaults.standardUserDefaults()
// MARK: - Static keys
/// Extend this class and add your user defaults keys as static constants
/// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`)
public class DefaultsKeys {
private init() {}
}
/// Base class for static user defaults keys. Specialize with value type type
/// and pass key name to the initializer to create a key.
public class DefaultsKey<ValueType>: DefaultsKeys {
// TODO: Can we use protocols to ensure ValueType is a compatible type?
public let _key: String
public init(_ key: String) {
self._key = key
}
}
extension NSUserDefaults {
func set<T>(key: DefaultsKey<T>, _ value: Any?) {
self[key._key] = value
}
}
extension NSUserDefaults {
/// Returns `true` if `key` exists
public func hasKey<T>(key: DefaultsKey<T>) -> Bool {
return objectForKey(key._key) != nil
}
/// Removes value for `key`
public func remove<T>(key: DefaultsKey<T>) {
removeObjectForKey(key._key)
}
}
// MARK: Static subscripts for standard types
// TODO: Use generic subscripts when they become available
extension NSUserDefaults {
public subscript(key: DefaultsKey<String?>) -> String? {
get { return stringForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<String>) -> String {
get { return stringForKey(key._key) ?? "" }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSString?>) -> NSString? {
get { return stringForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSString>) -> NSString {
get { return stringForKey(key._key) ?? "" }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Int?>) -> Int? {
get { return numberForKey(key._key)?.integerValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Int>) -> Int {
get { return numberForKey(key._key)?.integerValue ?? 0 }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Double?>) -> Double? {
get { return numberForKey(key._key)?.doubleValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Double>) -> Double {
get { return numberForKey(key._key)?.doubleValue ?? 0.0 }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Bool?>) -> Bool? {
get { return numberForKey(key._key)?.boolValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Bool>) -> Bool {
get { return numberForKey(key._key)?.boolValue ?? false }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<AnyObject?>) -> AnyObject? {
get { return objectForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSObject?>) -> NSObject? {
get { return objectForKey(key._key) as? NSObject }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSData?>) -> NSData? {
get { return dataForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSData>) -> NSData {
get { return dataForKey(key._key) ?? NSData() }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSDate?>) -> NSDate? {
get { return objectForKey(key._key) as? NSDate }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSURL?>) -> NSURL? {
get { return URLForKey(key._key) }
set { set(key, newValue) }
}
// TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String])
public subscript(key: DefaultsKey<[String: AnyObject]?>) -> [String: AnyObject]? {
get { return dictionaryForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[String: AnyObject]>) -> [String: AnyObject] {
get { return dictionaryForKey(key._key) ?? [:] }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSDictionary?>) -> NSDictionary? {
get { return dictionaryForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSDictionary>) -> NSDictionary {
get { return dictionaryForKey(key._key) ?? [:] }
set { set(key, newValue) }
}
}
// MARK: Static subscripts for array types
extension NSUserDefaults {
public subscript(key: DefaultsKey<NSArray?>) -> NSArray? {
get { return arrayForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<NSArray>) -> NSArray {
get { return arrayForKey(key._key) ?? [] }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[AnyObject]?>) -> [AnyObject]? {
get { return arrayForKey(key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[AnyObject]>) -> [AnyObject] {
get { return arrayForKey(key._key) ?? [] }
set { set(key, newValue) }
}
}
// We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to
// suppress compiler warnings about NSArray not being convertible to [T]
// AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value
// types bridge-able to Foundation types (String, Int, ...)
extension NSUserDefaults {
public func getArray<T: _ObjectiveCBridgeable>(key: DefaultsKey<[T]>) -> [T] {
return arrayForKey(key._key) as NSArray? as? [T] ?? []
}
public func getArray<T: _ObjectiveCBridgeable>(key: DefaultsKey<[T]?>) -> [T]? {
return arrayForKey(key._key) as NSArray? as? [T]
}
public func getArray<T: AnyObject>(key: DefaultsKey<[T]>) -> [T] {
return arrayForKey(key._key) as NSArray? as? [T] ?? []
}
public func getArray<T: AnyObject>(key: DefaultsKey<[T]?>) -> [T]? {
return arrayForKey(key._key) as NSArray? as? [T]
}
}
extension NSUserDefaults {
public subscript(key: DefaultsKey<[String]?>) -> [String]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[String]>) -> [String] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Int]?>) -> [Int]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Int]>) -> [Int] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Double]?>) -> [Double]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Double]>) -> [Double] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Bool]>) -> [Bool] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[NSData]?>) -> [NSData]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[NSData]>) -> [NSData] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[NSDate]?>) -> [NSDate]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[NSDate]>) -> [NSDate] {
get { return getArray(key) }
set { set(key, newValue) }
}
}
// MARK: Archiving complex types
extension NSUserDefaults {
// TODO: Can we simplify this and ensure that T is NSCoding compliant?
public func archive<T>(key: DefaultsKey<T>, _ value: T) {
if let value: AnyObject = value as? AnyObject {
set(key, NSKeyedArchiver.archivedDataWithRootObject(value))
} else {
assertionFailure("Invalid value type, needs to be a NSCoding-compliant type")
}
}
public func archive<T>(key: DefaultsKey<T?>, _ value: T?) {
if let value: AnyObject = value as? AnyObject {
set(key, NSKeyedArchiver.archivedDataWithRootObject(value))
} else if value == nil {
remove(key)
} else {
assertionFailure("Invalid value type, needs to be a NSCoding-compliant type")
}
}
public func unarchive<T>(key: DefaultsKey<T?>) -> T? {
return dataForKey(key._key).flatMap { NSKeyedUnarchiver.unarchiveObjectWithData($0) } as? T
}
public func unarchive<T>(key: DefaultsKey<T>) -> T? {
return dataForKey(key._key).flatMap { NSKeyedUnarchiver.unarchiveObjectWithData($0) } as? T
}
}
// MARK: - Deprecations
infix operator ?= {
associativity right
precedence 90
}
/// If key doesn't exist, sets its value to `expr`
/// Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory.
/// Note: If key already exists, the expression after ?= isn't evaluated
@available(*, deprecated=1, message="Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60")
public func ?= (proxy: NSUserDefaults.Proxy, @autoclosure expr: () -> Any) {
if !proxy.defaults.hasKey(proxy.key) {
proxy.defaults[proxy.key] = expr()
}
}
/// Adds `b` to the key (and saves it as an integer)
/// If key doesn't exist or isn't a number, sets value to `b`
@available(*, deprecated=1, message="Please migrate to static keys to use this.")
public func += (proxy: NSUserDefaults.Proxy, b: Int) {
let a = proxy.defaults[proxy.key].intValue
proxy.defaults[proxy.key] = a + b
}
@available(*, deprecated=1, message="Please migrate to static keys to use this.")
public func += (proxy: NSUserDefaults.Proxy, b: Double) {
let a = proxy.defaults[proxy.key].doubleValue
proxy.defaults[proxy.key] = a + b
}
/// Icrements key by one (and saves it as an integer)
/// If key doesn't exist or isn't a number, sets value to 1
@available(*, deprecated=1, message="Please migrate to static keys to use this.")
public postfix func ++ (proxy: NSUserDefaults.Proxy) {
proxy += 1
}
| mit | c58d1f5eed81230c11872a8b6b7749c1 | 30.234127 | 167 | 0.594016 | 4.403357 | false | false | false | false |
LongPF/FaceTube | FaceTube/Home/FTLiveDetailViewController.swift | 1 | 3211 | //
// FTLiveDetailViewController.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/3/15.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
import SnapKit
class FTLiveDetailViewController: FTViewController {
var player: IJKFFMoviePlayerController!
var homeLiveModel: FTHomeLiveModel?
fileprivate var backgroundImageView: UIImageView?
fileprivate var visualEffectView: UIVisualEffectView?
//MARK: ************************ life cycle ************************
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.backgroundColor()
backgroundImageView = UIImageView()
backgroundImageView?.backgroundColor = UIColor.clear
view.addSubview(backgroundImageView!)
backgroundImageView?.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
let blurEffect: UIBlurEffect = UIBlurEffect.init(style: .light)
visualEffectView = UIVisualEffectView.init(effect: blurEffect)
backgroundImageView?.addSubview(visualEffectView!)
visualEffectView?.snp.makeConstraints({ (make) in
make.edges.equalTo(backgroundImageView!)
})
let backButton = UIButton.init(frame: CGRect.init(x: 15, y: 20, width: 44, height: 44))
backButton.setImage(UIImage.init(named: "ft_round_btn_back_n"), for: .normal)
backButton.addTarget(self, action: #selector(FTLiveDetailViewController.gotoBack(button:)), for: .touchUpInside)
view.addSubview(backButton)
initPlayer()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
if player != nil{
player.play()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
player.pause()
}
deinit
{
if player != nil {
player.stop()
player = nil
}
}
//MARK: ************************ private methods *****************
func initPlayer() {
if homeLiveModel != nil {
let url = NSURL.init(string: (homeLiveModel?.stream_addr)!)
let player = IJKFFMoviePlayerController.init(contentURL: url as URL!, with: nil)
self.player = player;
self.player.prepareToPlay()
self.player.view.frame = UIScreen.main.bounds
self.view.insertSubview(self.player.view, at: 1)
}
}
//MARK: ************************ response methods ***************
func gotoBack(button: UIButton){
_ = navigationController?.popViewController(animated: true)
}
//MARK:转场动画
override func captureViewAnimationFrame() -> CGRect {
return UIScreen.main.bounds
}
override func magicMoveTransionComplete() {
let url = URL(string: (homeLiveModel?.creator?.portrait)!)
backgroundImageView?.kf.setImage(with: url);
}
}
| mit | ab5781623476159ab95352ad8cb99e20 | 30.009709 | 120 | 0.596118 | 5.037855 | false | false | false | false |
CaryZheng/VaporDemo | Sources/App/Middleware/MyMiddleware.swift | 1 | 1530 | //
// MyMiddleware.swift
// App
//
// Created by CaryZheng on 2018/4/2.
//
import Vapor
import Validation
class MyMiddleware: Middleware, Service {
func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
let promise = request.eventLoop.newPromise(Response.self)
func handleError(_ error: Swift.Error) {
let res = request.makeResponse()
res.http.headers.replaceOrAdd(name: .contentType, value: "application/json")
let reason: String = error.localizedDescription
var protocolCode = ProtocolCode.failInternalError
if error is ValidationError
|| error is MyException {
protocolCode = ProtocolCode.failParamError
}
let bodyStr = ResponseWrapper<DefaultResponseObj>(protocolCode: protocolCode, msg: reason).makeResponse()
res.http.body = HTTPBody(string: bodyStr)
promise.succeed(result: res)
}
do {
try next.respond(to: request).do { res in
res.http.headers.replaceOrAdd(name: .contentType, value: "application/json")
promise.succeed(result: res)
}.catch { error in
handleError(error)
}
} catch {
handleError(error)
}
return promise.futureResult
}
}
| mit | e3a000bda66baf6a479b1c62a5c66109 | 28.423077 | 117 | 0.547712 | 5.186441 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/CropViewController.swift | 2 | 7653 | //
// CropViewController.swift
// edX
//
// Created by Michael Katz on 10/19/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
private class CircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = OEXStyles.sharedStyles().neutralBlack().colorWithAlphaComponent(0.8)
userInteractionEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var circleBounds: CGRect {
let rect = bounds
let minSize = min(rect.width, rect.height)
let hole = CGRectInset(CGRect(x: (rect.width - minSize) / 2, y: (rect.height - minSize) / 2, width: minSize, height: minSize), 6, 6)
return hole
}
private override func drawRect(rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
CGContextSaveGState(context)
let hole = circleBounds
CGContextAddEllipseInRect(context, hole);
CGContextClip(context);
CGContextClearRect(context, hole);
CGContextSetFillColorWithColor( context, UIColor.clearColor().CGColor);
CGContextFillRect( context, hole);
CGContextSetStrokeColorWithColor(context, OEXStyles.sharedStyles().neutralLight().CGColor)
CGContextStrokeEllipseInRect(context, hole)
CGContextRestoreGState(context)
}
}
class CropViewController: UIViewController {
var image: UIImage
let imageView: UIImageView
let scrollView: UIScrollView
let titleLabel: UILabel
let completion: UIImage? -> Void
private let circleView: CircleView
init(image: UIImage, completion: UIImage? -> Void) {
self.image = image
self.completion = completion
imageView = UIImageView(image: image)
scrollView = UIScrollView()
circleView = CircleView()
titleLabel = UILabel()
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.addSubview(imageView)
scrollView.contentSize = image.size
scrollView.delegate = self
view.addSubview(scrollView)
view.backgroundColor = OEXStyles.sharedStyles().neutralBlack()
let toolbar = buildToolbar()
view.addSubview(circleView)
view.addSubview(toolbar)
let titleStyle = OEXStyles.sharedStyles().navigationTitleTextStyle
titleLabel.attributedText = titleStyle.attributedStringWithText(Strings.Profile.cropAndResizePicture)
view.addSubview(titleLabel)
titleLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_topMargin).offset(20)
make.centerX.equalTo(view.snp_centerX)
}
scrollView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view)
make.left.equalTo(view)
make.right.equalTo(view)
make.bottom.equalTo(view)
}
toolbar.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(view)
make.trailing.equalTo(view)
make.bottom.equalTo(view)
make.height.equalTo(50)
}
circleView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(scrollView)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(CropViewController.zoomOut))
tap.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(tap)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false)
}
private func buildToolbar() -> UIToolbar {
let toolbar = UIToolbar()
toolbar.barTintColor = UIColor.clearColor()
toolbar.tintColor = OEXStyles.sharedStyles().neutralWhiteT()
let cancelButton = UIButton(type:.System)
cancelButton.frame = CGRect(x: 0,y: 0, width: 100, height: 44)
cancelButton.setTitle(Strings.cancel, forState: .Normal)
cancelButton.setTitleColor(OEXStyles.sharedStyles().neutralWhiteT(), forState: .Normal)
cancelButton.sizeToFit()
let cancel = UIBarButtonItem(customView: cancelButton)
cancelButton.oex_addAction({ [weak self] _ in
self?.completion(nil)
}, forEvents: .TouchUpInside)
let chooseButton = UIButton(type:.System)
chooseButton.frame = CGRect(x: 0,y: 0, width: 100, height: 44)
chooseButton.setTitle(Strings.choose, forState: .Normal)
chooseButton.setTitleColor(OEXStyles.sharedStyles().neutralWhiteT(), forState: .Normal)
chooseButton.sizeToFit()
let choose = UIBarButtonItem(customView: chooseButton)
chooseButton.oex_addAction({ [weak self] _ in
let rect = self!.circleView.circleBounds
let shift = CGRectApplyAffineTransform(rect, CGAffineTransformMakeTranslation(self!.scrollView.contentOffset.x, self!.scrollView.contentOffset.y))
let scaled = CGRectApplyAffineTransform(shift, CGAffineTransformMakeScale(1.0 / self!.scrollView.zoomScale, 1.0 / self!.scrollView.zoomScale))
let newImage = self?.image.imageCroppedToRect(scaled)
self?.completion(newImage)
}, forEvents: .TouchUpInside)
let flex = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
var items = [cancel, flex, choose]
if toolbar.isRightToLeft {
items = items.reverse()
}
toolbar.items = items
return toolbar
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
OEXAnalytics.sharedAnalytics().trackScreenWithName(OEXAnalyticsScreenCropPhoto)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let scrollFrame = scrollView.frame
let hole = circleView.circleBounds
let imSize = image.size
guard hole.width > 0 else { return }
let verticalRatio = hole.height / imSize.height
let horizontalRatio = hole.width / imSize.width
scrollView.minimumZoomScale = max(horizontalRatio, verticalRatio)
scrollView.maximumZoomScale = 1
scrollView.zoomScale = scrollView.minimumZoomScale
let insetHeight = (scrollFrame.height - hole.height) / 2
let insetWidth = (scrollFrame.width - hole.width) / 2
scrollView.contentInset = UIEdgeInsetsMake(insetHeight, insetWidth, insetHeight, insetWidth)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CropViewController: UIScrollViewDelegate {
func zoomOut() {
let newScale = scrollView.zoomScale == scrollView.minimumZoomScale ? 0.5 : scrollView.minimumZoomScale
scrollView.setZoomScale(newScale, animated: true)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
//need empty implementation for zooming
}
}
| apache-2.0 | fdf1c3b0288664182c86304fba233161 | 35.788462 | 158 | 0.653947 | 5.251887 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/ExtraStringAPIs.swift | 1 | 1324 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Random access for String.UTF16View, only when Foundation is
// imported. Making this API dependent on Foundation decouples the
// Swift core from a UTF16 representation.
extension String.UTF16View.Index : Strideable {
/// Construct from an integer offset.
public init(_ offset: Int) {
_precondition(offset >= 0, "Negative UTF16 index offset not allowed")
self.init(_offset: offset)
}
public func distance(to other: String.UTF16View.Index) -> Int {
return other._offset.distance(to: _offset)
}
public func advanced(by n: Int) -> String.UTF16View.Index {
return String.UTF16View.Index(_offset.advanced(by: n))
}
}
extension String.UTF16View : RandomAccessCollection {}
extension String.UTF16View.Indices : RandomAccessCollection {}
| apache-2.0 | 76ec564fc0f641ea4cf8b34332075e61 | 37.941176 | 80 | 0.624622 | 4.597222 | false | false | false | false |
flutter/plugins | packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift | 2 | 10750 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
import XCTest
@testable import quick_actions_ios
class QuickActionsPluginTests: XCTestCase {
func testHandleMethodCall_setShortcutItems() {
let rawItem = [
"type": "SearchTheThing",
"localizedTitle": "Search the thing",
"icon": "search_the_thing.png",
]
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let call = FlutterMethodCall(methodName: "setShortcutItems", arguments: [rawItem])
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let parseShortcutItemsExpectation = expectation(
description: "parseShortcutItems must be called.")
mockShortcutItemParser.parseShortcutItemsStub = { items in
XCTAssertEqual(items as? [[String: String]], [rawItem])
parseShortcutItemsExpectation.fulfill()
return [item]
}
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [item], "Must set shortcut items.")
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_clearShortcutItems() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let call = FlutterMethodCall(methodName: "clearShortcutItems", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
mockShortcutItemProvider.shortcutItems = [item]
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [], "Must clear shortcut items.")
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_getLaunchAction() {
let call = FlutterMethodCall(methodName: "getLaunchAction", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_nonExistMethods() {
let call = FlutterMethodCall(methodName: "nonExist", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertEqual(
result as? NSObject, FlutterMethodNotImplemented,
"result block must be called with FlutterMethodNotImplemented")
resultExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testApplicationPerformActionForShortcutItem() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
mockChannel.invokeMethodStub = { method, arguments in
XCTAssertEqual(method, "launch")
XCTAssertEqual(arguments as? String, item.type)
invokeMethodExpectation.fulfill()
}
let actionResult = plugin.application(
UIApplication.shared,
performActionFor: item
) { success in /* no-op */ }
XCTAssert(actionResult, "performActionForShortcutItem must return true.")
waitForExpectations(timeout: 1)
}
func testApplicationDidFinishLaunchingWithOptions_launchWithShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
}
func testApplicationDidFinishLaunchingWithOptions_launchWithoutShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:])
XCTAssert(
launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.")
}
func testApplicationDidBecomeActive_launchWithoutShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
mockChannel.invokeMethodStub = { _, _ in
XCTFail("invokeMethod should not be called if launch without shortcut.")
}
let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:])
XCTAssert(
launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
}
func testApplicationDidBecomeActive_launchWithShortcut() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
mockChannel.invokeMethodStub = { method, arguments in
XCTAssertEqual(method, "launch")
XCTAssertEqual(arguments as? String, item.type)
invokeMethodExpectation.fulfill()
}
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
waitForExpectations(timeout: 1)
}
func testApplicationDidBecomeActive_launchWithShortcut_becomeActiveTwice() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
var invokeMehtodCount = 0
mockChannel.invokeMethodStub = { method, arguments in
invokeMehtodCount += 1
invokeMethodExpectation.fulfill()
}
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
waitForExpectations(timeout: 1)
XCTAssertEqual(invokeMehtodCount, 1, "shortcut should only be handled once per launch.")
}
}
| bsd-3-clause | 41246e21b4fb35402f057f3f99bb522e | 35.564626 | 100 | 0.746977 | 6.146369 | false | false | false | false |
HeartRateLearning/HRLApp | HRLAppTests/TestDoubles/Common/Classifier/Persistence/DataFramePersistentStoreTestDouble.swift | 1 | 868 | //
// DataFramePersistentStoreTestDouble.swift
// HRLApp
//
// Created by Enrique de la Torre (dev) on 09/02/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import Foundation
import HRLClassifier
@testable import HRLApp
// MARK: - Main body
final class DataFramePersistentStoreTestDouble {
// MARK: - Public properties
fileprivate (set) var readCount = 0
fileprivate (set) var writeCount = 0
fileprivate (set) var lastWriteDataFrame: DataFrame?
var readResult = DataFrame()
}
// MARK: - DataFramePersistentStoreProtocol methods
extension DataFramePersistentStoreTestDouble: DataFramePersistentStoreProtocol {
func read() -> DataFrame {
readCount += 1
return readResult
}
func write(_ dataFrame: DataFrame) {
writeCount += 1
lastWriteDataFrame = dataFrame
}
}
| mit | d6a043dff8a87bea439ce5da5f348d77 | 19.642857 | 80 | 0.700115 | 4.636364 | false | true | false | false |
google/iosched-ios | Source/IOsched/Common/TagButton.swift | 1 | 2757 | //
// Copyright (c) 2017 Google 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 MaterialComponents
class TagButton: MDCRaisedButton {
enum Constants {
static let lightTitleColor = UIColor.white
static let darkTitleColor = UIColor(hex: "#202124")
}
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = false
let font = UIFont.mdc_preferredFont(forMaterialTextStyle: .caption)
setTitleFont(font, for: .normal)
registerForDynamicTypeUpdates()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func setBackgroundColor(_ backgroundColor: UIColor?, for state: UIControl.State) {
super.setBackgroundColor(backgroundColor, for: state)
guard let backgroundColor = backgroundColor else {
setTitleColor(Constants.darkTitleColor, for: state)
return
}
if backgroundColor.shouldDisplayDarkText {
setTitleColor(Constants.darkTitleColor, for: state)
} else {
setTitleColor(Constants.lightTitleColor, for: state)
}
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
let superSize = super.intrinsicContentSize
guard let font = titleFont(for: .normal) else { return superSize }
let height = font.lineHeight + 8
return CGSize(width: superSize.width, height: height)
}
override var accessibilityTraits: UIAccessibilityTraits {
get {
return isUserInteractionEnabled
? UIAccessibilityTraits.button
: UIAccessibilityTraits.staticText
}
set {
}
}
func registerForDynamicTypeUpdates() {
NotificationCenter.default.addObserver(self,
selector: #selector(dynamicTypeTextSizeDidChange(_:)),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
@objc func dynamicTypeTextSizeDidChange(_ sender: Any) {
let font = UIFont.mdc_preferredFont(forMaterialTextStyle: .caption)
setTitleFont(font, for: .normal)
setNeedsLayout()
}
}
| apache-2.0 | cac5d4e5cba5270ceb91a31fdcfa54b0 | 30.329545 | 97 | 0.692057 | 4.81993 | false | false | false | false |
objecthub/swift-lispkit | Sources/LispKit/Primitives/BoxLibrary.swift | 1 | 4150 | //
// BoxLibrary.swift
// LispKit
//
// Created by Matthias Zenger on 18/07/2016.
// Copyright © 2016 ObjectHub. All rights reserved.
//
// 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.
//
///
/// Box library: based on Racket spec.
///
public final class BoxLibrary: NativeLibrary {
/// Name of the library.
public override class var name: [String] {
return ["lispkit", "box"]
}
/// Dependencies of the library.
public override func dependencies() {
self.`import`(from: ["lispkit", "core"], "define", "apply-with-values")
}
/// Declarations of the library.
public override func declarations() {
// Boxes
self.define(Procedure("box?", self.isBox))
self.define(Procedure("box", self.box))
self.define(Procedure("unbox", self.unbox))
self.define(Procedure("set-box!", self.setBox))
self.define("update-box!", via:
"(define (update-box! box proc) (set-box! box (apply-with-values proc (unbox box))))")
// Mutable pairs
self.define(Procedure("mpair?", self.isMpair))
self.define(Procedure("mcons", self.mcons))
self.define(Procedure("mcar", self.mcar))
self.define(Procedure("mcdr", self.mcdr))
self.define(Procedure("set-mcar!", self.setMcar))
self.define(Procedure("set-mcdr!", self.setMcdr))
}
//-------- MARK: - Boxes
private func box(_ args: Arguments) -> Expr {
return .box(Cell(args.values))
}
private func unbox(_ expr: Expr) throws -> Expr {
guard case .box(let cell) = expr else {
throw RuntimeError.type(expr, expected: [.boxType])
}
return cell.value
}
private func setBox(_ expr: Expr, args: Arguments) throws -> Expr {
guard case .box(let cell) = expr else {
throw RuntimeError.type(expr, expected: [.boxType])
}
// Set cell value. Guarantee that cells for which `set-box!` is called are managed
// by a managed object pool.
let value = args.values
(value.isAtom ? cell : self.context.objects.manage(cell)).value = value
return .void
}
private func isBox(_ expr: Expr) -> Expr {
guard case .box(_) = expr else {
return .false
}
return .true
}
//-------- MARK: - Mutable pairs
private func isMpair(_ expr: Expr) -> Expr {
guard case .mpair(_) = expr else {
return .false
}
return .true
}
private func mcons(_ car: Expr, cdr: Expr) throws -> Expr {
return .mpair(Tuple(car, cdr))
}
private func mcar(_ expr: Expr) throws -> Expr {
guard case .mpair(let tuple) = expr else {
throw RuntimeError.type(expr, expected: [.mpairType])
}
return tuple.fst
}
private func mcdr(_ expr: Expr) throws -> Expr {
guard case .mpair(let tuple) = expr else {
throw RuntimeError.type(expr, expected: [.mpairType])
}
return tuple.snd
}
private func setMcar(_ expr: Expr, value: Expr) throws -> Expr {
guard case .mpair(let tuple) = expr else {
throw RuntimeError.type(expr, expected: [.mpairType])
}
// Set car of tuple. Guarantee that tuples for which `set-mcar!` is called are managed
// by a managed object pool.
(value.isAtom ? tuple : self.context.objects.manage(tuple)).fst = value
return .void
}
private func setMcdr(_ expr: Expr, value: Expr) throws -> Expr {
guard case .mpair(let tuple) = expr else {
throw RuntimeError.type(expr, expected: [.mpairType])
}
// Set cdr of tuple. Guarantee that tuples for which `set-mcdr!` is called are managed
// by a managed object pool.
(value.isAtom ? tuple : self.context.objects.manage(tuple)).snd = value
return .void
}
}
| apache-2.0 | bda1c50dd2959bec86d1147fac239804 | 30.195489 | 92 | 0.643047 | 3.744585 | false | false | false | false |
jarocht/iOS-Bootcamp-Summer2015 | RocketShipDemo/RocketShipDemo/main.swift | 1 | 1037 | //
// main.swift
// RocketShipDemo
//
// Created by X Code User on 7/14/15.
// Copyright (c) 2015 gvsu.edu. All rights reserved.
//
// Tim Jaroch & Remo Hoeppli
// Lab02
import Foundation
var countDown: [String] = ["ten","nine","eight","seven","six","five","four","three","two","one"]
/*var rocket: Rocket = Rocket(fuel: 100) //100 Gallons!
rocket.blastOff()*/
/*rocket.programmableBlastOff { (input: Int) -> Void in
var fuel = input
println("Fuel Tank @ \(fuel) units")
for v in countDown{
fuel = fuel - 10
println(v)
println("Fuel Tank @ \(fuel) units")
}
}*/
/*var fancyRocket: Rocket = MannedRocket(fuel: 2000, astro1:"Tim", astro2:"Remo")
fancyRocket.programmableBlastOff{ (Int) -> Void in
for v in countDown{
println(v)
}
}*/
var teamRocket: Rocket = BestRocket(fuel: 100, astro1: "Remo", astro2: "Tim", destination: "Pluto", rocketName: "Millenium Falcon")
teamRocket.programmableBlastOff { (Int) -> Void in
for v in countDown {
println(v)
}
}
| gpl-2.0 | 3402dbf95755d0a011c487c6cf7978fa | 23.690476 | 131 | 0.625844 | 3.142424 | false | false | false | false |
ngageoint/fog-machine | Demo/FogViewshed/FogViewshed/Models/HGT/HGTFile.swift | 1 | 3776 | import Foundation
import MapKit
/**
Has information concerning an HGT file on the filesystem
*/
class HGTFile: NSObject {
let path:NSURL
// File names refer to the latitude and longitude of the lower left corner of
// the tile - e.g. N37W105 has its lower left corner at 37 degrees north
// latitude and 105 degrees west longitude
var filename:String {
return path.lastPathComponent!
}
init(path: NSURL) {
self.path = path
super.init()
}
static func coordinateToFilename(coordinate:CLLocationCoordinate2D, resolution:Int) -> String {
// adjust the boundary. Don't run this near the poles...
let correctedCoordinate:CLLocationCoordinate2D = CLLocationCoordinate2DMake(floor(coordinate.latitude + (1.0/Double(resolution))*0.5), floor(coordinate.longitude + (1.0/Double(resolution))*0.5))
var filename = ""
if (correctedCoordinate.latitude < 0.0) {
filename += "S"
} else {
filename += "N"
}
filename += String(format: "%02d", Int(abs(correctedCoordinate.latitude)))
if (correctedCoordinate.longitude < 0.0) {
filename += "W"
} else {
filename += "E"
}
filename += String(format: "%03d", Int(abs(correctedCoordinate.longitude)))
filename += ".hgt"
return filename
}
func getFileSizeInBytes() -> UInt64 {
var fileSize : UInt64 = 0
do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(path.path!)
if let _attr = attr {
fileSize = _attr.fileSize();
}
} catch {
print("Error: \(error)")
}
return fileSize
}
// Get adjusted resolution of the file. Files contain signed two byte integers
func getResolution() -> Int {
return Int(sqrt(Double(getFileSizeInBytes()/2))) - 1
}
private func getLowerLeftCoordinate() -> CLLocationCoordinate2D {
let nOrS:String = filename.substringWithRange(filename.startIndex ..< filename.startIndex.advancedBy(1))
var lat:Double = Double(filename.substringWithRange(filename.startIndex.advancedBy(1) ..< filename.startIndex.advancedBy(3)))!
if (nOrS.uppercaseString == "S") {
lat *= -1.0
}
lat = lat - (1.0/Double(getResolution()))*0.5
let wOrE:String = filename.substringWithRange(filename.startIndex.advancedBy(3) ..< filename.startIndex.advancedBy(4))
var lon:Double = Double(filename.substringWithRange(filename.startIndex.advancedBy(4) ..< filename.startIndex.advancedBy(7)))!
if (wOrE.uppercaseString == "W") {
lon *= -1.0
}
lon = lon - (1.0/Double(getResolution()))*0.5
return CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
func getBoundingBox() -> AxisOrientedBoundingBox {
let llCoordinate:CLLocationCoordinate2D = getLowerLeftCoordinate()
return AxisOrientedBoundingBox(lowerLeft: llCoordinate, upperRight: CLLocationCoordinate2DMake(llCoordinate.latitude+1.0, llCoordinate.longitude+1.0))
}
func latLonToIndex(latLon:CLLocationCoordinate2D) -> (Int, Int) {
return HGTManager.latLonToIndex(latLon, boundingBox: getBoundingBox(), resolution: getResolution())
}
override func isEqual(object: AnyObject?) -> Bool {
if let object = object as? HGTFile {
return self.filename == object.filename
} else {
return false
}
}
override var hash: Int {
return filename.hashValue
}
} | mit | b0cbbadf29ccf266f9572a9cbf729c08 | 33.651376 | 202 | 0.610699 | 4.588092 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/MGBookViews/MGBookViews/UITextField+XLExtension.swift | 1 | 2994 | //
// UITextField+XLExtension.swift
// LoanApp
//
// Created by newunion on 2017/12/18.
// Copyright © 2017年 Tassel. All rights reserved.
//
import UIKit
typealias CallBackBlock = ((Any)->())
extension UITextField {
// 改进写法【推荐】
fileprivate struct RuntimeKey {
static let Right_Eye_CallBackBlock = UnsafeRawPointer.init(bitPattern: "Right_Eye_CallBackBlock".hashValue)
static let Right_clear_CallBackBlock = UnsafeRawPointer.init(bitPattern: "Right_clear_CallBackBlock".hashValue)
/// ...其他Key声明
}
func loadRightEyeButton() {
let eyeButton = UIButton(type: .custom)
eyeButton.setImage(UIImage(named: "user_password_hide"), for: .normal)
eyeButton.setImage(UIImage(named: "user_password_show"), for: .selected)
eyeButton.sizeToFit()
eyeButton.addTarget(self, action: #selector(self.showHidePassword), for: .touchUpInside)
rightView = eyeButton
rightViewMode = .always
}
@objc func showHidePassword(_ sender: UIButton) {
let text: String = self.text!
sender.isSelected = !sender.isSelected
isSecureTextEntry = !sender.isSelected
self.text = text
let backBlock: CallBackBlock? = objc_getAssociatedObject(self, UITextField.RuntimeKey.Right_Eye_CallBackBlock!) as? CallBackBlock
if backBlock != nil {
backBlock!(sender.isSelected)
}
}
func loadRightEyeButton(withCallBack backBlock: CallBackBlock?) {
objc_setAssociatedObject(self, UITextField.RuntimeKey.Right_Eye_CallBackBlock!, backBlock, .OBJC_ASSOCIATION_RETAIN) as? CallBackBlock
loadRightEyeButton()
}
func loadRightClearButton() {
let clearButton = UIButton(type: .custom)
clearButton.setImage(UIImage(named: "login_textField_clear"), for: .normal)
// [clearButton setImage:[UIImage new] forState:UIControlStateSelected];
clearButton.sizeToFit()
clearButton.addTarget(self, action: #selector(self.setClearInput), for: .touchUpInside)
addTarget(self, action: #selector(textFieldChange(_:)), for: .editingChanged)
rightView = clearButton
rightViewMode = .whileEditing
}
@objc func setClearInput(_ btn: UIButton) {
let inputStr: String = text!
text = ""
rightView?.isHidden = true
let backBlock: CallBackBlock? = objc_getAssociatedObject(self, UITextField.RuntimeKey.Right_clear_CallBackBlock!) as? CallBackBlock
if backBlock != nil {
backBlock!(inputStr)
}
}
func loadRightClearButton(withCallBack backBlock: @escaping CallBackBlock) {
objc_setAssociatedObject(self, UITextField.RuntimeKey.Right_clear_CallBackBlock!, backBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
loadRightClearButton()
}
@objc fileprivate func textFieldChange(_ textF: UITextField) {
rightView?.isHidden = !textF.hasText
}
}
| mit | 0b32237ad9e3e5aee7aad399d20c2a9b | 38.039474 | 142 | 0.675093 | 4.687204 | false | false | false | false |
audrl1010/EasyMakePhotoPicker | Example/EasyMakePhotoPicker/FacebookPhotoCell.swift | 1 | 5039 | //
// FacebookPhotoCell.swift
// EasyMakePhotoPicker
//
// Created by myung gi son on 2017. 7. 6..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import UIKit
import Photos
import RxSwift
import EasyMakePhotoPicker
class FacebookPhotoCell: BaseCollectionViewCell, PhotoCellable {
// MARK: - Constant
struct Constant {
static let selectedViewBorderWidth = CGFloat(5)
}
struct Color {
static let selectedViewBorderColor = UIColor(
red: 104/255,
green: 156/255,
blue: 255/255,
alpha: 1.0)
}
struct Metric {
static let orderLabelWidth = CGFloat(30)
static let orderLabelHeight = CGFloat(30)
}
// MARK: - Properties
var selectedView = UIView().then {
$0.layer.borderWidth = Constant.selectedViewBorderWidth
$0.layer.borderColor = Color.selectedViewBorderColor.cgColor
$0.isHidden = true
}
var orderLabel = FacebookNumberLabel().then {
$0.clipsToBounds = false
$0.isHidden = true
}
var imageView = UIImageView().then {
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
var disposeBag: DisposeBag = DisposeBag()
var viewModel: PhotoCellViewModel? {
didSet {
guard let viewModel = viewModel else { return }
bind(viewModel: viewModel)
}
}
// MARK: - Life Cycle
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
viewModel = nil
imageView.image = nil
orderLabel.text = nil
orderLabel.isHidden = true
selectedView.isHidden = true
}
override func addSubviews() {
addSubview(imageView)
addSubview(selectedView)
addSubview(orderLabel)
}
override func setupConstraints() {
imageView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
selectedView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
orderLabel
.fs_widthAnchor(
equalToConstant: Metric.orderLabelWidth)
.fs_heightAnchor(
equalToConstant: Metric.orderLabelHeight)
.fs_rightAnchor(
equalTo: rightAnchor)
.fs_topAnchor(
equalTo: topAnchor)
.fs_endSetup()
}
// MARK: - Bind
func bind(viewModel: PhotoCellViewModel) {
viewModel.isSelect
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self, weak viewModel] isSelect in
guard let `self` = self,
let `viewModel` = viewModel else { return }
self.selectedView.isHidden = !isSelect
if viewModel.configure.allowsMultipleSelection {
self.orderLabel.isHidden = !isSelect
}
else {
self.orderLabel.isHidden = true
}
})
.disposed(by: disposeBag)
viewModel.isSelect
.skip(1)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] isSelect in
guard let `self` = self else { return }
if isSelect {
self.cellAnimationWhenSelectedCell()
}
else {
self.cellAnimationWhenDeselectedCell()
}
})
.disposed(by: disposeBag)
viewModel.selectedOrder
.subscribe(onNext: { [weak self] selectedOrder in
guard let `self` = self else { return }
self.orderLabel.text = "\(selectedOrder)"
})
.disposed(by: disposeBag)
viewModel.image.asObservable()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] image in
guard let `self` = self else { return }
self.imageView.image = image
})
.disposed(by: disposeBag)
}
}
// MARK: - Animation
extension FacebookPhotoCell {
var cellAnimationWhenSelectedCell: () -> () {
return {
UIView.SpringAnimator(duration: 0.3)
.options(.curveEaseOut)
.velocity(0.0)
.damping(0.5)
.beforeAnimations { [weak self] in
guard let `self` = self else { return }
self.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}
.animations { [weak self] in
guard let `self` = self else { return }
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
.animate()
}
}
var cellAnimationWhenDeselectedCell: () -> () {
return {
UIView.SpringAnimator(duration: 0.3)
.options(.curveEaseOut)
.velocity(0.0)
.damping(0.5)
.beforeAnimations { [weak self] in
guard let `self` = self else { return }
self.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}
.animations { [weak self] in
guard let `self` = self else { return }
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
.animate()
}
}
}
| mit | 606062f5cabcbd278aa85e13b584284b | 22.643192 | 67 | 0.613582 | 4.390584 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/BinarySearchTreeDepth/LinkedList/BinarySearchTreeDepthLinkedList.swift | 1 | 1322 | //
// BinarySearchTreeDepthLinkedList.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 01/06/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class BinarySearchTreeDepthLinkedList: NSObject {
// MARK: Properties
var head: BinarySearchTreeDepthLinkedListNode?
// MARK: Action
func addNode(binarySearchNode: BinarySearchTreeDepthNode) {
addNode(binarySearchNode: binarySearchNode, linkedListNode: head)
}
private func addNode(binarySearchNode: BinarySearchTreeDepthNode, linkedListNode: BinarySearchTreeDepthLinkedListNode?) {
if let linkedListNode = linkedListNode {
if linkedListNode.next == nil {
let node = BinarySearchTreeDepthLinkedListNode()
node.binarySearchTreeNode = binarySearchNode
linkedListNode.next = node
}
else {
addNode(binarySearchNode: binarySearchNode, linkedListNode: linkedListNode.next)
}
}
else {
let node = BinarySearchTreeDepthLinkedListNode()
node.binarySearchTreeNode = binarySearchNode
head = node
}
}
}
| mit | 06426b2efaa0a5dfd2c3ae0be0939c37 | 26.520833 | 125 | 0.601817 | 6.507389 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | MapsAndPlacesDemo/MapsAndPlacesDemo/OverlayController.swift | 1 | 5696 | /* Copyright (c) 2020 Google 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 UIKit
import GooglePlaces
import GoogleMaps
class OverlayController {
private var overlays = [GMSCircle]()
private var lat: Double = 0.0
private var long: Double = 0.0
// MARK: Methods to get the placeID from a set of coordinates
/// Searches an API for the entire data JSON file based on the lat and long values
///
/// - Parameter completion: The completion handler.
func fetchData(completion: @escaping ([String : Any]?, Error?) -> Void) {
var apiKey: String = ApiKeys.mapsAPI
let url = "https://maps.googleapis.com/maps/api/geocode/json?&latlng=\(lat),\(long)&key="
let search = URL(string: url + apiKey)!
let task = URLSession.shared.dataTask(with: search) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(
with: data,
options: .allowFragments
) as? [String : Any] {
completion(array, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
/// Finds and parses data to extract a placeId from a set of coordinates and sends the appropriate data to the completion handler
///
/// - Parameters:
/// - latitude: The latitude of the location.
/// - longitude: The longitude of the location.
/// - completion: The completion handler.
func geocode(
latitude: Double,
longitude: Double,
completion: @escaping (_ placemark: [CLPlacemark]?, _ error: Error?, _ pid: String) -> Void
) {
CLGeocoder().reverseGeocodeLocation(
CLLocation(
latitude: latitude,
longitude: longitude
)
) { placemark, error in
guard let placemark = placemark, error == nil else {
completion(nil, error, "")
return
}
self.lat = latitude
self.long = longitude
var ans: String = ""
self.fetchData { (dict, error) in
let convert = String(describing: dict?["results"])
var counter: Int = 0
// I want to find the key "place_id" somewhere in the JSON file
var characters = [Character]()
let search = "place_id"
for letter in search {
characters.append(letter)
}
var startPlaceId: Bool = false
for ch in convert {
if !startPlaceId {
// Counter resembles the index of the "place_id" we are currently looking
// for; if the character matches, then counter is incremented
if ch == characters[counter] {
counter += 1
} else {
counter = 0
if ch == "p" {
counter = 1
}
}
// If counter's length is equal to the length of "place_id," we've found it
if counter >= characters.count {
startPlaceId = true
}
} else {
// Once we've found "place_id," we want to build the actual place_id, so we
// need to ignore the punctuation
if ch == ":" {
continue
} else if ch == ";" {
break
} else {
ans += String(ch)
}
}
}
completion(placemark, nil, ans)
}
}
}
// MARK: - Draw and erase functions
/// Draws a circle on a map
///
/// - Parameters:
/// - mapView: The mapView to draw on.
/// - darkModeToggle: If on, the color of the circle should be white; otherwise, the color of the circle should be black.
/// - coord: The coordinates of the center of the circle.
/// - rad: The radius of the circle.
func drawCircle(
mapView: GMSMapView,
darkModeToggle: Bool,
coord: CLLocationCoordinate2D,
rad: Double = 2000
) {
let circle = GMSCircle()
circle.map = nil
circle.position = coord
circle.radius = rad
circle.fillColor = .clear
circle.strokeColor = darkModeToggle ? .white : .black
circle.strokeWidth = 3.4
circle.map = mapView
overlays.append(circle)
}
/// Clears all overlays created (for now, the only possible overlay is the circle)
func clear() {
for x in overlays {
x.map = nil
}
}
}
| apache-2.0 | 34b943912c417279999ee5cb39020ee3 | 35.748387 | 133 | 0.504916 | 5.15942 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/DealerComponent/Presenter/DealerDetailPresenter.swift | 1 | 6685 | import ComponentBase
import EurofurenceModel
import Foundation
class DealerDetailPresenter: DealerDetailSceneDelegate {
private struct Binder: DealerDetailSceneBinder {
var viewModel: DealerDetailViewModel
func bindComponent<T>(
at index: Int,
using componentFactory: T
) -> T.Component where T: DealerDetailItemComponentFactory {
let visitor = BindingDealerDetailVisitor(componentFactory, viewModel: viewModel)
viewModel.describeComponent(at: index, to: visitor)
guard let component = visitor.boundComponent else {
fatalError("Unable to bind component for DealerDetailScene at index \(index)")
}
return component
}
}
class BindingDealerDetailVisitor<T>: DealerDetailViewModelVisitor where T: DealerDetailItemComponentFactory {
private let componentFactory: T
private let viewModel: DealerDetailViewModel
private(set) var boundComponent: T.Component?
init(_ componentFactory: T, viewModel: DealerDetailViewModel) {
self.componentFactory = componentFactory
self.viewModel = viewModel
}
func visit(_ summary: DealerDetailSummaryViewModel) {
boundComponent = componentFactory.makeDealerSummaryComponent { (component) in
component.setDealerTitle(summary.title)
component.setDealerCategories(summary.categories)
component.hideArtistArtwork()
component.hideDealerSubtitle()
component.hideDealerShortDescription()
component.hideTwitterHandle()
component.hideTelegramHandle()
component.hideDealerWebsite()
component.onWebsiteSelected(perform: viewModel.openWebsite)
component.onTwitterSelected(perform: viewModel.openTwitter)
component.onTelegramSelected(perform: viewModel.openTelegram)
if let artworkData = summary.artistImagePNGData {
component.showArtistArtworkImageWithPNGData(artworkData)
}
if let subtitle = summary.subtitle {
component.showDealerSubtitle(subtitle)
}
if let shortDescription = summary.shortDescription {
component.showDealerShortDescription(shortDescription)
}
if let website = summary.website {
component.showDealerWebsite(website)
}
if let twitterHandle = summary.twitterHandle {
component.showDealerTwitterHandle(twitterHandle)
}
if let telegramHandle = summary.telegramHandle {
component.showDealerTelegramHandle(telegramHandle)
}
}
}
func visit(_ location: DealerDetailLocationAndAvailabilityViewModel) {
boundComponent = componentFactory.makeDealerLocationAndAvailabilityComponent { (component) in
component.setComponentTitle(location.title)
component.hideMap()
component.hideLimitedAvailbilityWarning()
component.hideAfterDarkDenNotice()
if let mapPNGGraphicData = location.mapPNGGraphicData {
component.showMapPNGGraphicData(mapPNGGraphicData)
}
if let limitedAvailabilityWarning = location.limitedAvailabilityWarning {
component.showDealerLimitedAvailabilityWarning(limitedAvailabilityWarning)
}
if let locatedInAfterDarkDealersDenMessage = location.locatedInAfterDarkDealersDenMessage {
component.showLocatedInAfterDarkDealersDenMessage(locatedInAfterDarkDealersDenMessage)
}
}
}
func visit(_ aboutTheArtist: DealerDetailAboutTheArtistViewModel) {
boundComponent = componentFactory.makeAboutTheArtistComponent { (component) in
component.setAboutTheArtistTitle(aboutTheArtist.title)
component.setArtistDescription(aboutTheArtist.artistDescription)
}
}
func visit(_ aboutTheArt: DealerDetailAboutTheArtViewModel) {
boundComponent = componentFactory.makeAboutTheArtComponent { (component) in
component.setComponentTitle(aboutTheArt.title)
component.hideAboutTheArtDescription()
component.hideArtPreviewImage()
component.hideArtPreviewCaption()
if let aboutTheArt = aboutTheArt.aboutTheArt {
component.showAboutTheArtDescription(aboutTheArt)
}
if let artPreviewImagePNGData = aboutTheArt.artPreviewImagePNGData {
component.showArtPreviewImagePNGData(artPreviewImagePNGData)
}
if let artPreviewCaption = aboutTheArt.artPreviewCaption {
component.showArtPreviewCaption(artPreviewCaption)
}
}
}
}
private weak var scene: DealerDetailScene?
private let dealerDetailViewModelFactory: DealerDetailViewModelFactory
private let dealer: DealerIdentifier
private let dealerInteractionRecorder: DealerInteractionRecorder
private var dealerInteraction: Interaction?
private var viewModel: DealerDetailViewModel?
init(
scene: DealerDetailScene,
dealerDetailViewModelFactory: DealerDetailViewModelFactory,
dealer: DealerIdentifier,
dealerInteractionRecorder: DealerInteractionRecorder
) {
self.scene = scene
self.dealerDetailViewModelFactory = dealerDetailViewModelFactory
self.dealer = dealer
self.dealerInteractionRecorder = dealerInteractionRecorder
scene.setDelegate(self)
}
func dealerDetailSceneDidLoad() {
dealerInteraction = dealerInteractionRecorder.makeInteraction(for: dealer)
dealerInteraction?.donate()
dealerDetailViewModelFactory.makeDealerDetailViewModel(for: dealer) { (viewModel) in
self.viewModel = viewModel
self.scene?.bind(numberOfComponents: viewModel.numberOfComponents, using: Binder(viewModel: viewModel))
}
}
func dealerDetailSceneDidAppear() {
dealerInteraction?.activate()
}
func dealerDetailSceneDidDisappear() {
dealerInteraction?.deactivate()
}
func dealerDetailSceneDidTapShareButton(_ sender: Any) {
viewModel?.shareDealer(sender)
}
}
| mit | 454d2616e16980072363f8594591fbb7 | 37.866279 | 115 | 0.65086 | 6.738911 | false | false | false | false |
danielrcardenas/ac-course-2017 | frameworks/SwarmChemistry-Swif/Demo/PlatformSpecific.swift | 1 | 424 | //
// PlatformSpecific.swift
// SwarmChemistry
//
// Created by Yamazaki Mitsuyoshi on 2017/08/10.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
typealias View = UIView
typealias Nib = UINib
typealias Window = UIWindow
#elseif os(macOS)
import Cocoa
typealias View = NSView
typealias Nib = NSNib
typealias Window = NSWindow
#endif
| apache-2.0 | f99ffccdc06c2ff52c50ec6f32f07880 | 21.263158 | 62 | 0.70922 | 3.916667 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/AppDelegate.swift | 1 | 4604 | //
// AppDelegate.swift
// UIScrollViewDemo
//
// Created by 伯驹 黄 on 2016/11/29.
// Copyright © 2016年 伯驹 黄. All rights reserved.
//
let UIFontMake: (CGFloat) -> UIFont = { UIFont.systemFont(ofSize: $0) }
let UIFontBoldMake: (CGFloat) -> UIFont = { UIFont.boldSystemFont(ofSize: $0) }
let SCREEN_WIDTH = UIScreen.main.bounds.width
let PADDING: CGFloat = 16
import UIKit
enum ValidateType {
case email, phoneNumber, idCard, password, number, englishName
}
extension String {
func validate(with type: ValidateType, autoShowAlert: Bool = true) -> Bool {
let regular: String
switch type {
case .email:
regular = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
case .phoneNumber:
regular = "^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0-9])\\d{8}$"
case .idCard:
regular = "^(^\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$"
case .number:
regular = "^\\d+(\\.\\d+)?$"
case .password:
regular = "^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,20}"
case .englishName:
regular = "^[a-zA-Z\\u4E00-\\u9FA5]{2,20}"
}
let regexEmail = NSPredicate(format: "SELF MATCHES %@", regular)
if regexEmail.evaluate(with: self) {
return true
} else {
return false
}
}
}
struct Response: Decodable {
let pageInstances: [Int]
let url: String
let benefitId: String?
let canClaim: Bool
let styleInfo: StyleInfo?
let type: SurpriseType
enum SurpriseType: String, Decodable {
case none
case common = "COMMON"
case activity = "ACTIVITY"
}
enum CodingKeys: String, CodingKey {
case pageInstances
case url
case benefitId
case canClaim
case styleInfo
case type
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
benefitId = try values.decodeIfPresent(String.self, forKey: .benefitId)
canClaim = try values.decodeIfPresent(Bool.self, forKey: .canClaim) ?? false
pageInstances = try values.decodeIfPresent([Int].self, forKey: .pageInstances) ?? []
styleInfo = try values.decodeIfPresent(StyleInfo.self, forKey: .styleInfo)
type = try values.decodeIfPresent(SurpriseType.self, forKey: .type) ?? .none
url = try values.decodeIfPresent(String.self, forKey: .url) ?? ""
}
}
struct StyleInfo: Codable {
let decorate: String?
let errorBoxPic: String?
let open: String?
let quotaErrorBoxPic: String?
let start: String?
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
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:.
}
}
| mit | d1c69bf1d871a0f0b51b51f4aa003283 | 35.712 | 285 | 0.662236 | 4.349763 | false | false | false | false |
kylef/Stencil | Sources/Expression.swift | 1 | 8054 | public protocol Expression: CustomStringConvertible {
func evaluate(context: Context) throws -> Bool
}
protocol InfixOperator: Expression {
init(lhs: Expression, rhs: Expression)
}
protocol PrefixOperator: Expression {
init(expression: Expression)
}
final class StaticExpression: Expression, CustomStringConvertible {
let value: Bool
init(value: Bool) {
self.value = value
}
func evaluate(context: Context) throws -> Bool {
return value
}
var description: String {
return "\(value)"
}
}
final class VariableExpression: Expression, CustomStringConvertible {
let variable: Resolvable
init(variable: Resolvable) {
self.variable = variable
}
var description: String {
return "(variable: \(variable))"
}
/// Resolves a variable in the given context as boolean
func resolve(context: Context, variable: Resolvable) throws -> Bool {
let result = try variable.resolve(context)
var truthy = false
if let result = result as? [Any] {
truthy = !result.isEmpty
} else if let result = result as? [String: Any] {
truthy = !result.isEmpty
} else if let result = result as? Bool {
truthy = result
} else if let result = result as? String {
truthy = !result.isEmpty
} else if let value = result, let result = toNumber(value: value) {
truthy = result > 0
} else if result != nil {
truthy = true
}
return truthy
}
func evaluate(context: Context) throws -> Bool {
return try resolve(context: context, variable: variable)
}
}
final class NotExpression: Expression, PrefixOperator, CustomStringConvertible {
let expression: Expression
init(expression: Expression) {
self.expression = expression
}
var description: String {
return "not \(expression)"
}
func evaluate(context: Context) throws -> Bool {
return try !expression.evaluate(context: context)
}
}
final class InExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) in \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
if let lhs = lhs as? VariableExpression, let rhs = rhs as? VariableExpression {
let lhsValue = try lhs.variable.resolve(context)
let rhsValue = try rhs.variable.resolve(context)
if let lhs = lhsValue as? AnyHashable, let rhs = rhsValue as? [AnyHashable] {
return rhs.contains(lhs)
} else if let lhs = lhsValue as? Int, let rhs = rhsValue as? CountableClosedRange<Int> {
return rhs.contains(lhs)
} else if let lhs = lhsValue as? Int, let rhs = rhsValue as? CountableRange<Int> {
return rhs.contains(lhs)
} else if let lhs = lhsValue as? String, let rhs = rhsValue as? String {
return rhs.contains(lhs)
} else if lhsValue == nil && rhsValue == nil {
return true
}
}
return false
}
}
final class OrExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) or \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
let lhs = try self.lhs.evaluate(context: context)
if lhs {
return lhs
}
return try rhs.evaluate(context: context)
}
}
final class AndExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) and \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
let lhs = try self.lhs.evaluate(context: context)
if !lhs {
return lhs
}
return try rhs.evaluate(context: context)
}
}
class EqualityExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
required init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) == \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
if let lhs = lhs as? VariableExpression, let rhs = rhs as? VariableExpression {
let lhsValue = try lhs.variable.resolve(context)
let rhsValue = try rhs.variable.resolve(context)
if let lhs = lhsValue, let rhs = rhsValue {
if let lhs = toNumber(value: lhs), let rhs = toNumber(value: rhs) {
return lhs == rhs
} else if let lhs = lhsValue as? String, let rhs = rhsValue as? String {
return lhs == rhs
} else if let lhs = lhsValue as? Bool, let rhs = rhsValue as? Bool {
return lhs == rhs
}
} else if lhsValue == nil && rhsValue == nil {
return true
}
}
return false
}
}
class NumericExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
required init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) \(symbol) \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
if let lhs = lhs as? VariableExpression, let rhs = rhs as? VariableExpression {
let lhsValue = try lhs.variable.resolve(context)
let rhsValue = try rhs.variable.resolve(context)
if let lhs = lhsValue, let rhs = rhsValue {
if let lhs = toNumber(value: lhs), let rhs = toNumber(value: rhs) {
return compare(lhs: lhs, rhs: rhs)
}
}
}
return false
}
var symbol: String {
return ""
}
func compare(lhs: Number, rhs: Number) -> Bool {
return false
}
}
class MoreThanExpression: NumericExpression {
override var symbol: String {
return ">"
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs > rhs
}
}
class MoreThanEqualExpression: NumericExpression {
override var symbol: String {
return ">="
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs >= rhs
}
}
class LessThanExpression: NumericExpression {
override var symbol: String {
return "<"
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs < rhs
}
}
class LessThanEqualExpression: NumericExpression {
override var symbol: String {
return "<="
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs <= rhs
}
}
class InequalityExpression: EqualityExpression {
override var description: String {
return "(\(lhs) != \(rhs))"
}
override func evaluate(context: Context) throws -> Bool {
return try !super.evaluate(context: context)
}
}
// swiftlint:disable:next cyclomatic_complexity
func toNumber(value: Any) -> Number? {
if let value = value as? Float {
return Number(value)
} else if let value = value as? Double {
return Number(value)
} else if let value = value as? UInt {
return Number(value)
} else if let value = value as? Int {
return Number(value)
} else if let value = value as? Int8 {
return Number(value)
} else if let value = value as? Int16 {
return Number(value)
} else if let value = value as? Int32 {
return Number(value)
} else if let value = value as? Int64 {
return Number(value)
} else if let value = value as? UInt8 {
return Number(value)
} else if let value = value as? UInt16 {
return Number(value)
} else if let value = value as? UInt32 {
return Number(value)
} else if let value = value as? UInt64 {
return Number(value)
} else if let value = value as? Number {
return value
} else if let value = value as? Float64 {
return Number(value)
} else if let value = value as? Float32 {
return Number(value)
}
return nil
}
| bsd-2-clause | 4d1e45ddfe04df77cbb502cbf4e373bf | 24.090343 | 94 | 0.642538 | 4.162274 | false | false | false | false |
TouchInstinct/LeadKit | Tests/Cursors/StubCursor.swift | 1 | 2635 | //
// Copyright (c) 2017 Touch Instinct
//
// 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 LeadKit
import RxSwift
class StubCursor: ResettableCursorType {
typealias Element = Post
private var posts: [Post] = []
private let maxItemsCount: Int
private let requestDelay: DispatchTimeInterval
var count: Int {
return posts.count
}
var exhausted: Bool {
return count >= maxItemsCount
}
subscript(index: Int) -> Post {
return posts[index]
}
init(maxItemsCount: Int = 12, requestDelay: DispatchTimeInterval = .seconds(2)) {
self.maxItemsCount = maxItemsCount
self.requestDelay = requestDelay
}
required init(resetFrom other: StubCursor) {
self.maxItemsCount = other.maxItemsCount
self.requestDelay = other.requestDelay
}
func loadNextBatch() -> Single<[Post]> {
return Single.create { observer -> Disposable in
if self.exhausted {
observer(.error(CursorError.exhausted))
} else {
DispatchQueue.global().asyncAfter(deadline: .now() + self.requestDelay, execute: {
let countBefore = self.count
let newPosts = Post.generate()
let maxNewPosts = min(self.maxItemsCount, countBefore + newPosts.count)
self.posts = Array((self.posts + newPosts)[0..<maxNewPosts])
observer(.success(self[countBefore..<self.count]))
})
}
return Disposables.create()
}
}
}
| apache-2.0 | cf14f1fae90c2ffb56a3f62b00348efd | 31.9375 | 98 | 0.659583 | 4.713775 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS | iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/PoolingLayer.swift | 1 | 7529 | //
// PoolingLayer.swift
// MemkiteMetal
//
// Created by Amund Tveit on 25/11/15.
// Copyright © 2015 memkite. All rights reserved.
//
import Foundation
import Metal
func createPoolingLayerCached(layer: NSDictionary,
inputBuffer: MTLBuffer,
inputShape: [Float],
metalCommandQueue: MTLCommandQueue, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice,
pool_type_caches: inout [Dictionary<String,String>],
layer_data_caches: inout [Dictionary<String,MTLBuffer>],
layer_number: Int,
layer_string: String,
caching_mode:Bool) -> (MTLBuffer, MTLCommandBuffer, [Float]) {
print(" ==> createPoolingLayerCached")
let metalCommandBuffer = metalCommandQueue.makeCommandBufferWithUnretainedReferences()
// let metalCommandBuffer = metalCommandQueue.commandBuffer()
var params = NSDictionary()
var stride:Float = 1.0
var kernel_size: Float = 1.0
var pad: Float = 0.0
var pooling_params = MetalPoolingParameters(kernel_size: kernel_size, pool_stride: stride, pad: pad)
var pool_type = 0
var h:Float = 0.0
var w:Float = 0.0
var shape:[Float] = []
var outputCount:Float = 0
var pool_width = 0
var pool_height = 0
var size_params:MetalShaderParameters = MetalShaderParameters(image_xdim:0.0, image_ydim:0.0, num_images: 0.0, filter_xdim: 0.0, filter_ydim: 0.0, num_filters: 0.0, conv_xdim: 0.0, conv_ydim: 0.0, pool_xdim: 0.0, pool_ydim: 0.0, b:0.0)
var outputBuffer:MTLBuffer
if(!caching_mode) {
params = layer["pooling_param"] as! NSDictionary
stride = 1.0
kernel_size = 1.0
pad = 0.0
if let val = params["stride"] {
stride = val as! Float
}
if let val = params["kernel_size"] {
kernel_size = val as! Float
if val as! NSNumber != 3 {
pad = 0
}
}
pooling_params = MetalPoolingParameters(kernel_size: kernel_size, pool_stride: stride, pad: pad)
pool_type = Int(params["pool"] as! Float)
// STORE pool type in cache!
pool_type_caches[layer_number]["pool_type"] = String(pool_type)
//TODO: calculate outputCount
h = ceil((inputShape[2] + 2.0 * pad - kernel_size) / stride) + 1.0
w = ceil((Float(inputShape[3]) + 2.0 * pad - kernel_size) / stride) + 1.0
shape = [inputShape[0], inputShape[1], h, w]
outputCount = shape.reduce(1, *)
pool_width = Int(shape[2])
pool_height = Int(shape[3])
size_params = MetalShaderParameters(image_xdim: Float(inputShape[2]), image_ydim: Float(inputShape[3]),
num_images: Float(inputShape[0]),
filter_xdim: 1.0, filter_ydim: 1.0, num_filters: Float(inputShape[1]),
conv_xdim:0.0, conv_ydim: 0.0,
pool_xdim: Float(pool_width), pool_ydim: Float(pool_height), b:0.0)
} else {
// need to fetch pool type from cache
print("FETCHING POOL TYPE FROM CACHE!!!!!")
pool_type = Int(pool_type_caches[layer_number]["pool_type"]!)!
}
if pool_type == 1 {
outputBuffer = addPoolingCommandToCommandBufferCached(commandBuffer: metalCommandBuffer, poolingMethod: "avg_pool", inputBuffer: inputBuffer, outputCount: Int(outputCount), size_params: size_params, pooling_params: pooling_params, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice,
layer_data_caches: &layer_data_caches, layer_number: layer_number, layer_string: layer_string)
} else {
outputBuffer = addPoolingCommandToCommandBufferCached(commandBuffer: metalCommandBuffer, poolingMethod: "max_pool", inputBuffer: inputBuffer, outputCount: Int(outputCount), size_params: size_params, pooling_params: pooling_params,metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice,
layer_data_caches: &layer_data_caches, layer_number: layer_number, layer_string: layer_string)
}
//metalCommandBuffer.commit()
print(" <== createPoolingLayerCached")
return (outputBuffer, metalCommandBuffer, shape)
}
func addPoolingCommandToCommandBufferCached(commandBuffer: MTLCommandBuffer,
poolingMethod: String,
inputBuffer: MTLBuffer,
outputCount: Int,
size_params: MetalShaderParameters,
pooling_params: MetalPoolingParameters,
metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice,
layer_data_caches: inout [Dictionary<String,MTLBuffer>],
layer_number: Int,
layer_string: String) -> MTLBuffer {
print(" ==> addPoolingCommandtoCommandBufferCached")
_ = layer_data_caches[layer_number]
let output = createFloatNumbersArray(outputCount)
let (_, computePipelineState, _) = setupShaderInMetalPipeline(poolingMethod, metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice)
let outputMetalBuffer = createOrReuseFloatMetalBuffer("outputMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice)
// let outputMetalBuffer = createFloatMetalBuffer(output, metalDevice: metalDevice)
let sizeParamMetalBuffer = createOrReuseShaderParametersMetalBuffer("sizeParamMetalBuffer", data: size_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice)
// let sizeParamMetalBuffer = createShaderParametersMetalBuffer(size_params, metalDevice: metalDevice)
// let poolingParamMetalBuffer = createPoolingParametersMetalBuffer(pooling_params, metalDevice: metalDevice)
let poolingParamMetalBuffer = createOrReusePoolingParametersMetalBuffer("poolingParamMetalBuffer", data: pooling_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice)
// Create Metal Compute Command Encoder and add input and output buffers to it
let metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder()
metalComputeCommandEncoder.setBuffer(outputMetalBuffer, offset: 0, at: 0)
metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, at: 1)
metalComputeCommandEncoder.setBuffer(sizeParamMetalBuffer, offset: 0, at: 2)
metalComputeCommandEncoder.setBuffer(poolingParamMetalBuffer, offset: 0, at: 3)
// Set the shader function that Metal will use
metalComputeCommandEncoder.setComputePipelineState(computePipelineState!)
// Set up thread groups on GPU
// TODO: check out http://metalbyexample.com/introduction-to-compute/
let threadsPerGroup = MTLSize(width:(computePipelineState?.threadExecutionWidth)!,height:1,depth:1)
// ensure at least 1 threadgroup
let numThreadgroups = MTLSize(width:(outputCount-1)/(computePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1)
metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup)
// Finalize configuration
metalComputeCommandEncoder.endEncoding()
print(" <== addPoolingCommandtoCommandBufferCached")
return outputMetalBuffer
}
| apache-2.0 | 325f1cfad8b504a75b2c5a5a56e38710 | 48.854305 | 309 | 0.656881 | 4.82255 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/28399-getpointerelementtype-is-not-storagetype.swift | 38 | 566 | // 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-swift-frontend %s -emit-ir
protocol A{associatedtype B
}
struct C<T:A>{
}
protocol E{associatedtype F
func g<T>(_:C<T>) where F==T.B
}
struct H:E{
typealias F = Void
func g<T>(_:C<T>) where F==T.B{}
}
| apache-2.0 | 79c18363385c6328b4d51dd2868b3712 | 28.789474 | 79 | 0.717314 | 3.309942 | false | false | false | false |
austinzheng/swift | test/NameBinding/name_lookup_min_max_conditional_conformance.swift | 8 | 2700 | // RUN: %target-typecheck-verify-swift
extension Range {
func f(_ value: Bound) -> Bound {
return max(lowerBound, min(value, upperBound))
// expected-warning@-1{{use of 'max' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Range' which comes via a conditional conformance}}
// expected-note@-2{{use 'Swift.' to continue to reference the global function}}
// expected-warning@-3{{use of 'min' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Range' which comes via a conditional conformance}}
// expected-note@-4{{use 'Swift.' to continue to reference the global function}}
}
}
protocol ContainsMinMax {}
extension ContainsMinMax {
func max() {}
func min() {}
}
func foo(_: Int, _: Int) {}
// expected-note@-1 {{'foo' declared here}}
protocol ContainsFoo {}
extension ContainsFoo {
func foo() {}
}
struct NonConditional: ContainsMinMax, ContainsFoo {}
extension NonConditional {
func f() {
_ = max(1, 2)
// expected-error@-1{{use of 'max' refers to instance method}}
// expected-note@-2{{use 'Swift.' to reference the global function}}
_ = min(3, 4)
// expected-error@-1{{use of 'min' refers to instance method}}
// expected-note@-2{{use 'Swift.' to reference the global function}}
_ = foo(5, 6)
// expected-error@-1{{use of 'foo' refers to instance method}}
// expected-note@-2{{use 'name_lookup_min_max_conditional_conformance.' to reference the global function}}
}
}
struct Conditional<T> {}
extension Conditional: ContainsMinMax where T: ContainsMinMax {}
extension Conditional: ContainsFoo where T: ContainsFoo {}
extension Conditional {
func f() {
_ = max(1, 2)
// expected-warning@-1{{use of 'max' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Conditional' which comes via a conditional conformance}}
// expected-note@-2{{use 'Swift.' to continue to reference the global function}}
_ = min(3, 4)
// expected-warning@-1{{use of 'min' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Conditional' which comes via a conditional conformance}}
// expected-note@-2{{use 'Swift.' to continue to reference the global function}}
_ = foo(5, 6)
// expected-error@-1{{type 'T' does not conform to protocol 'ContainsFoo'}}
}
}
| apache-2.0 | 1eb87a740a42979ab46f045166a04a32 | 45.551724 | 239 | 0.674074 | 4.199067 | false | false | false | false |
tardieu/swift | test/Parse/subscripting.swift | 6 | 3427 | // RUN: %target-typecheck-verify-swift
struct X { }
// Simple examples
struct X1 {
var stored: Int
subscript(i: Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored: Int
subscript(i: Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored: Int
subscript(_: Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored: Int
subscript(i: Int, j: Int) -> Int {
get {
return stored + i + j
}
mutating
set(v) {
stored = v + i - j
}
}
}
struct Y1 {
var stored: Int
subscript(_: i, j: Int) -> Int { // expected-error {{use of undeclared type 'i'}}
get {
return stored + j
}
set {
stored = j
}
}
}
// Mutating getters on constants (https://bugs.swift.org/browse/SR-845)
struct Y2 {
subscript(_: Int) -> Int {
mutating get { return 0 }
}
}
let y2 = Y2() // expected-note{{change 'let' to 'var' to make it mutable}}{{1-4=var}}
_ = y2[0] // expected-error{{cannot use mutating getter on immutable value: 'y2' is a 'let' constant}}
// Parsing errors
struct A0 {
subscript // expected-error {{expected '(' for subscript parameters}}
i : Int
-> Int {
get {
return stored
}
set {
stored = value
}
}
subscript -> Int { // expected-error {{expected '(' for subscript parameters}} {{12-12=()}}
return 1
}
}
struct A1 {
subscript (i : Int) // expected-error{{expected '->' for subscript element type}}
Int {
get {
return stored
}
set {
stored = value
}
}
}
struct A2 {
subscript (i : Int) -> // expected-error{{expected subscripting element type}}
{
get {
return stored
}
set {
stored = value
}
}
}
struct A3 {
subscript(i : Int) // expected-error {{expected '->' for subscript element type}}
{
get {
return i
}
}
}
struct A4 {
subscript(i : Int) { // expected-error {{expected '->' for subscript element type}}
get {
return i
}
}
}
struct A5 {
subscript(i : Int) -> Int // expected-error {{expected '{' in subscript to specify getter and setter implementation}}
}
struct A6 {
subscript(i: Int)(j: Int) -> Int { // expected-error {{expected '->' for subscript element type}}
get {
return i + j
}
}
}
struct A7 {
static subscript(a: Int) -> Int { // expected-error {{subscript cannot be marked 'static'}} {{3-10=}}
get {
return 42
}
}
}
struct A7b {
class subscript(a: Float) -> Int { // expected-error {{subscript cannot be marked 'class'}} {{3-9=}}
get {
return 42
}
}
}
struct A8 {
subscript(i : Int) -> Int // expected-error{{expected '{' in subscript to specify getter and setter implementation}}
get {
return stored
}
set {
stored = value
}
}
struct A9 {
subscript x() -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}}
return 0
}
}
struct A10 {
subscript x(i: Int) -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}}
return 0
}
}
struct A11 {
subscript x y : Int -> Int { // expected-error {{expected '(' for subscript parameters}}
return 0
}
}
} // expected-error{{extraneous '}' at top level}} {{1-3=}}
| apache-2.0 | d5b6633345b2d0bb238688734ca96fa4 | 16.395939 | 119 | 0.550919 | 3.472138 | false | false | false | false |
LinDing/Positano | Positano/Helpers/YepAsset.swift | 1 | 672 | //
// YepAsset.swift
// Yep
//
// Created by NIX on 15/4/22.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import AVFoundation
func thumbnailImageOfVideoInVideoURL(_ videoURL: URL) -> UIImage? {
let asset = AVURLAsset(url: videoURL, options: [:])
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
var actualTime: CMTime = CMTimeMake(0, 0)
guard let cgImage = try? imageGenerator.copyCGImage(at: CMTimeMakeWithSeconds(0.0, 600), actualTime: &actualTime) else {
return nil
}
let thumbnail = UIImage(cgImage: cgImage)
return thumbnail
}
| mit | 5a73fe7e5319bcb45ca2616ff6f2ad07 | 23.814815 | 124 | 0.704478 | 4.1875 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/Content/RealmQuestColors.swift | 1 | 693 | //
// RealmQuestColors.swift
// Habitica Database
//
// Created by Phillip Thelen on 22.05.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmQuestColors: Object, QuestColorsProtocol {
@objc dynamic var key: String?
var dark: String?
var medium: String?
var light: String?
var extralight: String?
convenience init(key: String?, protocolObject: QuestColorsProtocol) {
self.init()
self.key = key
dark = protocolObject.dark
medium = protocolObject.medium
light = protocolObject.light
extralight = protocolObject.extralight
}
}
| gpl-3.0 | ba1054f735c220f22930a2f971830ae0 | 23.714286 | 73 | 0.680636 | 4.271605 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/FuzzILTool/main.swift | 1 | 6031 | // Copyright 2020 Google LLC
//
// 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
//
// https://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 Fuzzilli
let jsFileExtension = ".js"
let protoBufFileExtension = ".fuzzil.protobuf"
let jsPrefix = ""
let jsSuffix = ""
let jsLifter = JavaScriptLifter(prefix: jsPrefix,
suffix: jsSuffix,
inliningPolicy: InlineOnlyLiterals(),
ecmaVersion: ECMAScriptVersion.es6)
let fuzzILLifter = FuzzILLifter()
// Loads a serialized FuzzIL program from the given file
func loadProgram(from path: String) throws -> Program {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let proto = try Fuzzilli_Protobuf_Program(serializedData: data)
let program = try Program(from: proto)
return program
}
func loadAllPrograms(in dirPath: String) -> [(filename: String, program: Program)] {
var isDir: ObjCBool = false
if !FileManager.default.fileExists(atPath: dirPath, isDirectory:&isDir) || !isDir.boolValue {
print("\(dirPath) is not a directory!")
exit(-1)
}
let fileEnumerator = FileManager.default.enumerator(atPath: dirPath)
var results = [(String, Program)]()
while let filename = fileEnumerator?.nextObject() as? String {
guard filename.hasSuffix(protoBufFileExtension) else { continue }
let path = dirPath + "/" + filename
do {
let program = try loadProgram(from: path)
results.append((filename, program))
} catch FuzzilliError.programDecodingError(let reason) {
print("Failed to load program \(path): \(reason)")
} catch {
print("Failed to load program \(path) due to unexpected error: \(error)")
}
}
return results
}
// Take a program and lifts it to JavaScript
func liftToJS(_ prog: Program) -> String {
let res = jsLifter.lift(prog)
return res.trimmingCharacters(in: .whitespacesAndNewlines)
}
// Take a program and lifts it to FuzzIL's text format
func liftToFuzzIL(_ prog: Program) -> String {
let res = fuzzILLifter.lift(prog)
return res.trimmingCharacters(in: .whitespacesAndNewlines)
}
// Loads all .fuzzil.protobuf files in a directory, and lifts them to JS
// Returns the number of files successfully converted
func liftAllPrograms(in dirPath: String, with lifter: Lifter, fileExtension: String) -> Int {
var numLiftedPrograms = 0
for (filename, program) in loadAllPrograms(in: dirPath) {
let newFilePath = "\(dirPath)/\(filename.dropLast(protoBufFileExtension.count))\(fileExtension)"
let content = lifter.lift(program)
do {
try content.write(to: URL(fileURLWithPath: newFilePath), atomically: false, encoding: String.Encoding.utf8)
numLiftedPrograms += 1
} catch {
print("Failed to write file \(newFilePath): \(error)")
}
}
return numLiftedPrograms
}
func loadProgramOrExit(from path: String) -> Program {
do {
return try loadProgram(from: path)
} catch {
print("Failed to load program from \(path): \(error)")
exit(-1)
}
}
let args = Arguments.parse(from: CommandLine.arguments)
if args["-h"] != nil || args["--help"] != nil || args.numPositionalArguments != 1 || args.numOptionalArguments != 1 {
print("""
Usage:
\(args.programName) option path
Options:
--liftToFuzzIL : Lifts the given protobuf program to FuzzIL's text format and prints it
--liftToJS : Lifts the given protobuf program to JS and prints it
--liftCorpusToJS : Loads all .fuzzil.protobuf files in a directory and lifts them to .js files in that same directory
--dumpProtobuf : Dumps the raw content of the given protobuf file
--dumpProgram : Dumps the internal representation of the program stored in the given protobuf file
--checkCorpus : Attempts to load all .fuzzil.protobuf files in a directory and checks if they are statically valid
""")
exit(0)
}
let path = args[0]
// Covert a single IL protobuf file to FuzzIL's text format and print to stdout
if args.has("--liftToFuzzIL") {
let program = loadProgramOrExit(from: path)
print(liftToFuzzIL(program))
}
// Covert a single IL protobuf file to JS and print to stdout
else if args.has("--liftToJS") {
let program = loadProgramOrExit(from: path)
print(liftToJS(program))
}
// Lift all protobuf programs to JavaScript
else if args.has("--liftCorpusToJS") {
let numLiftedPrograms = liftAllPrograms(in: path, with: jsLifter, fileExtension: jsFileExtension)
print("Lifted \(numLiftedPrograms) programs to JS")
}
// Pretty print just the protobuf, without trying to load as a program
// This allows the debugging of produced programs that are not syntactically valid
else if args.has("--dumpProtobuf") {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let proto = try Fuzzilli_Protobuf_Program(serializedData: data)
dump(proto, maxDepth: 3)
}
// Pretty print a protobuf as a program on stdout
else if args.has("--dumpProgram") {
let program = loadProgramOrExit(from: path)
dump(program)
}
// Combine multiple protobuf programs into a single corpus file
else if args.has("--checkCorpus") {
let numPrograms = loadAllPrograms(in: path).count
print("Successfully loaded \(numPrograms) programs")
}
else {
print("Invalid option: \(args.unusedOptionals.first!)")
exit(-1)
}
| apache-2.0 | f29fdea3ceee25fd2c83b2b6d986b96f | 36.459627 | 137 | 0.678494 | 4.256175 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.