repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
mcgraw/dojo-custom-camera | dojo-custom-camera/XMCCameraViewController.swift | 3 | 3787 | //
// XMCCameraViewController.swift
// dojo-custom-camera
//
// Created by David McGraw on 11/13/14.
// Copyright (c) 2014 David McGraw. All rights reserved.
//
import UIKit
import AVFoundation
enum Status: Int {
case Preview, Still, Error
}
class XMCCameraViewController: UIViewController, XMCCameraDelegate {
@IBOutlet weak var cameraStill: UIImageView!
@IBOutlet weak var cameraPreview: UIView!
@IBOutlet weak var cameraStatus: UILabel!
@IBOutlet weak var cameraCapture: UIButton!
@IBOutlet weak var cameraCaptureShadow: UILabel!
var preview: AVCaptureVideoPreviewLayer?
var camera: XMCCamera?
var status: Status = .Preview
override func viewDidLoad() {
super.viewDidLoad()
self.initializeCamera()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.establishVideoPreviewArea()
}
func initializeCamera() {
self.cameraStatus.text = "Starting Camera"
self.camera = XMCCamera(sender: self)
}
func establishVideoPreviewArea() {
self.preview = AVCaptureVideoPreviewLayer(session: self.camera?.session)
self.preview?.videoGravity = AVLayerVideoGravityResizeAspectFill
self.preview?.frame = self.cameraPreview.bounds
self.preview?.cornerRadius = 8.0
self.cameraPreview.layer.addSublayer(self.preview!)
}
// MARK: Button Actions
@IBAction func captureFrame(sender: AnyObject) {
if self.status == .Preview {
self.cameraStatus.text = "Capturing Photo"
UIView.animateWithDuration(0.225, animations: { () -> Void in
self.cameraPreview.alpha = 0.0;
self.cameraStatus.alpha = 1.0
})
self.camera?.captureStillImage({ (image) -> Void in
if image != nil {
self.cameraStill.image = image;
UIView.animateWithDuration(0.225, animations: { () -> Void in
self.cameraStill.alpha = 1.0;
self.cameraStatus.alpha = 0.0;
})
self.status = .Still
} else {
self.cameraStatus.text = "Uh oh! Something went wrong. Try it again."
self.status = .Error
}
self.cameraCapture.setTitle("Reset", forState: UIControlState.Normal)
})
} else if self.status == .Still || self.status == .Error {
UIView.animateWithDuration(0.225, animations: { () -> Void in
self.cameraStill.alpha = 0.0;
self.cameraStatus.alpha = 0.0;
self.cameraPreview.alpha = 1.0;
self.cameraCapture.setTitle("Capture", forState: UIControlState.Normal)
}, completion: { (done) -> Void in
self.cameraStill.image = nil;
self.status = .Preview
})
}
}
// MARK: Camera Delegate
func cameraSessionConfigurationDidComplete() {
self.camera?.startCamera()
}
func cameraSessionDidBegin() {
self.cameraStatus.text = ""
UIView.animateWithDuration(0.225, animations: { () -> Void in
self.cameraStatus.alpha = 0.0
self.cameraPreview.alpha = 1.0
self.cameraCapture.alpha = 1.0
self.cameraCaptureShadow.alpha = 0.4;
})
}
func cameraSessionDidStop() {
self.cameraStatus.text = "Camera Stopped"
UIView.animateWithDuration(0.225, animations: { () -> Void in
self.cameraStatus.alpha = 1.0
self.cameraPreview.alpha = 0.0
})
}
}
| mit |
GabrielGhe/SwiftProjects | App13CardTilt/CardTilt/TipInCellAnimator.swift | 1 | 1464 | //
// TipInCellAnimator.swift
// CardTilt
//
// Created by Gabriel Gheorghian on 2014-09-08.
// Copyright (c) 2014 RayWenderlich.com. All rights reserved.
//
import UIKit
import QuartzCore
let TipInCellAnimatorStartTransform:CATransform3D = {
// Variables
let rotationDegrees: CGFloat = -15.0
let rotationRadians: CGFloat = rotationDegrees * (CGFloat(M_PI)/180.0)
let offset = CGPointMake(-20, -20)
var startTransform = CATransform3DIdentity
// Rotate Identity 15 degrees counter clockwise
startTransform = CATransform3DRotate(CATransform3DIdentity,
rotationRadians, 0.0, 0.0, 1.0)
// Translate the card a bit
startTransform = CATransform3DTranslate(startTransform, offset.x, offset.y, 0.0)
return startTransform
}()
class TipInCellAnimator {
class func animate(cell: UITableViewCell) {
let view = cell.contentView
view.layer.opacity = 0.1
UIView.animateWithDuration(1.4, animations: {
view.layer.opacity = 1
})
}
class func animateByRotating(cell: UITableViewCell) {
let view = cell.contentView
// Initial state
view.layer.transform = TipInCellAnimatorStartTransform
view.layer.opacity = 0.8
// Animate back to normal
UIView.animateWithDuration(0.4) {
view.layer.transform = CATransform3DIdentity
view.layer.opacity = 1
}
}
} | mit |
ihomway/RayWenderlichCourses | Intermediate Swift 3/Intermediate Swift 3.playground/Pages/Classes Challenge.xcplaygroundpage/Contents.swift | 1 | 892 | //: [Previous](@previous)
import UIKit
/*:
#### Intermediate Swift Video Tutorial Series - raywenderlich.com
#### Video 5: Classes
**Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu.
Make the following objects and determine whether they are structs or classes. For the properties, use properties unless noted below.
TShirt: size, color
Address: street, city, state, zipCode
User: firstName, lastName, address (Address object)
ShoppingCart: shirts (array of TShirt), User (user object)
*/
struct Tshirt {
}
struct Address {
var street: String = ""
var city: String = ""
var state: String = ""
var zipCode: Int = 0
}
class User {
var firstName = ""
var lastName = ""
var address: Address = Address()
}
class ShoppingCart {
var shirts: [Tshirt] = []
var user = User()
}
//: [Next](@next)
| mit |
sadawi/PrimarySource | Pod/iOS/ValueFieldCell.swift | 1 | 776 | //
// ValueFieldCell.swift
// Pods
//
// Created by Sam Williams on 3/14/17.
//
//
import UIKit
/**
Any cell that presents its value as a string that is not directly editable.
*/
open class ValueFieldCell<Value:Equatable>: FieldCell<Value> {
open var options:[Value] = [] {
didSet {
self.update()
}
}
open var textForNil: String?
open var textForValue:((Value) -> String)?
func formatValue(_ value: Value?) -> String {
if let value = value {
if let formatter = self.textForValue {
return formatter(value)
} else {
return String(describing: value)
}
} else {
return self.textForNil ?? ""
}
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/Media/MediaThumbnailExporter.swift | 2 | 11255 | import Foundation
import MobileCoreServices
/// Media export handling of thumbnail images from videos or images.
///
class MediaThumbnailExporter: MediaExporter {
/// Directory type for the ThumbnailExporter, defaults to the .cache directory.
///
var mediaDirectoryType: MediaDirectory = .cache
// MARK: Export Options
var options = Options()
/// Available options for an thumbnail export.
///
struct Options {
/// The preferred size of the image, in points, typically for the actual display
/// of the image within a layout's dimensions. If nil, the image will not be resized.
///
/// - Note: The final size may or may not match the preferred dimensions, depending
/// on the original image.
///
var preferredSize: CGSize?
/// The scale for the actual pixel size of the image when resizing,
/// generally matching a screen scale of 1.0, 2.0, 3.0, etc.
///
/// - Note: Defaults to the main UIScreen scale. The final image may or may not match
/// the intended scale/pixels, depending on the original image.
///
var scale: CGFloat = UIScreen.main.scale
/// The compression quality of the thumbnail, if the image type supports compression.
///
var compressionQuality = 0.90
/// The target image type of the exported thumbnail images.
///
/// - Note: Passed on to the MediaImageExporter.Options.exportImageType.
///
var thumbnailImageType = kUTTypeJPEG as String
/// Computed preferred size, at scale.
///
var preferredSizeAtScale: CGSize? {
guard let size = preferredSize else {
return nil
}
return CGSize(width: size.width * scale, height: size.height * scale)
}
/// Computed preferred maximum size, at scale.
///
var preferredMaximumSizeAtScale: CGFloat? {
guard let size = preferredSize else {
return nil
}
return max(size.width, size.height) * scale
}
lazy var identifier: String = {
return UUID().uuidString
}()
}
// MARK: - Types
/// A generated thumbnail identifier representing a reference to the image files that
/// result from a thumbnail export. This ensures unique files are created and URLs
/// can be recreated as needed, relative to both the identifier and the configured
/// options for an exporter.
///
/// - Note: Media objects should store or cache these identifiers in order to reuse
/// previously exported Media files that match the given identifier and configured options.
///
typealias ThumbnailIdentifier = String
/// Completion block with the generated thumbnail identifier and resulting image export.
///
typealias OnThumbnailExport = (ThumbnailIdentifier, MediaExport) -> Void
/// Errors specific to exporting thumbnails.
///
public enum ThumbnailExportError: MediaExportError {
case failedToGenerateThumbnailFileURL
case unsupportedThumbnailFromOriginalType
var description: String {
switch self {
default:
return NSLocalizedString("Thumbnail unavailable.", comment: "Message shown if a thumbnail preview of a media item unavailable.")
}
}
}
// MARK: - Public
/// The available file URL of a thumbnail, if it exists, relative to the identifier
/// and exporter's configured options.
///
/// - Note: Consider using this URL for cacheing exported images located at the URL.
///
func availableThumbnail(with identifier: ThumbnailIdentifier) -> URL? {
guard let thumbnail = try? thumbnailURL(withIdentifier: identifier) else {
return nil
}
guard let type = thumbnail.typeIdentifier, UTTypeConformsTo(type as CFString, options.thumbnailImageType as CFString) else {
return nil
}
return thumbnail
}
/// Check for whether or not a file URL supports a thumbnail export.
///
func supportsThumbnailExport(forFile url: URL) -> Bool {
do {
let expected = try MediaURLExporter.expectedExport(with: url)
switch expected {
case .image, .video, .gif:
return true
case .other:
return false
}
} catch {
return false
}
}
let url: URL?
init(url: URL? = nil) {
self.url = url
}
public func export(onCompletion: @escaping OnMediaExport, onError: @escaping OnExportError) -> Progress {
guard let fileURL = url else {
onError(exporterErrorWith(error: ThumbnailExportError.failedToGenerateThumbnailFileURL))
return Progress.discreteCompletedProgress()
}
return exportThumbnail(forFile: fileURL, onCompletion: { (identifier, export) in
onCompletion(export)
}, onError: onError)
}
/// Export a thumbnail image for a file at the URL, with an expected type of an image or video.
///
/// - Note: GIFs are currently unsupported and throw the .gifThumbnailsUnsupported error.
///
@discardableResult func exportThumbnail(forFile url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress {
do {
let expected = try MediaURLExporter.expectedExport(with: url)
switch expected {
case .image, .gif:
return exportImageThumbnail(at: url, onCompletion: onCompletion, onError: onError)
case .video:
return exportVideoThumbnail(at: url, onCompletion: onCompletion, onError: onError)
case .other:
return Progress.discreteCompletedProgress()
}
} catch {
onError(exporterErrorWith(error: error))
return Progress.discreteCompletedProgress()
}
}
/// Export an existing image as a thumbnail image, based on the exporter options.
///
@discardableResult func exportThumbnail(forImage image: UIImage, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress {
let exporter = MediaImageExporter(image: image, filename: UUID().uuidString)
exporter.mediaDirectoryType = .temporary
exporter.options = imageExporterOptions
return exporter.export(onCompletion: { (export) in
self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError)
}, onError: onError)
}
/// Export a known video at the URL, being either a file URL or a remote URL.
///
@discardableResult func exportThumbnail(forVideoURL url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress {
if url.isFileURL {
return exportThumbnail(forFile: url, onCompletion: onCompletion, onError: onError)
} else {
return exportVideoThumbnail(at: url, onCompletion: onCompletion, onError: onError)
}
}
// MARK: - Private
/// Export a thumbnail for a known image at the URL, using self.options for ImageExporter options.
///
@discardableResult fileprivate func exportImageThumbnail(at url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress {
let exporter = MediaImageExporter(url: url)
exporter.mediaDirectoryType = .temporary
exporter.options = imageExporterOptions
return exporter.export(onCompletion: { (export) in
self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError)
},
onError: onError)
}
/// Export a thumbnail for a known video at the URL, using self.options for ImageExporter options.
///
@discardableResult fileprivate func exportVideoThumbnail(at url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress {
let exporter = MediaVideoExporter(url: url)
exporter.mediaDirectoryType = .temporary
return exporter.exportPreviewImageForVideo(atURL: url,
imageOptions: imageExporterOptions,
onCompletion: { (export) in
self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError)
},
onError: onError)
}
/// The default options to use for exporting images based on the thumbnail exporter's options.
///
fileprivate var imageExporterOptions: MediaImageExporter.Options {
var imageOptions = MediaImageExporter.Options()
if let maximumSize = options.preferredMaximumSizeAtScale {
imageOptions.maximumImageSize = maximumSize
}
imageOptions.imageCompressionQuality = options.compressionQuality
imageOptions.exportImageType = options.thumbnailImageType
return imageOptions
}
/// A thumbnail URL written with the corresponding identifier and configured export options.
///
fileprivate func thumbnailURL(withIdentifier identifier: ThumbnailIdentifier) throws -> URL {
var filename = "thumbnail-\(identifier)"
if let preferredSize = options.preferredSizeAtScale {
filename.append("-\(Int(preferredSize.width))x\(Int(preferredSize.height))")
}
// Get a new URL for the file as a thumbnail within the cache.
return try mediaFileManager.makeLocalMediaURL(withFilename: filename,
fileExtension: URL.fileExtensionForUTType(options.thumbnailImageType),
incremented: false)
}
/// Renames and moves an exported thumbnail to the expected directory with the expected thumbnail filenaming convention.
///
fileprivate func exportImageToThumbnailCache(_ export: MediaExport, onCompletion: OnThumbnailExport, onError: OnExportError) {
do {
// Generate a unique ID
let identifier = options.identifier
let thumbnail = try thumbnailURL(withIdentifier: identifier)
let fileManager = FileManager.default
// Move the exported file at the url to the new URL.
try? fileManager.removeItem(at: thumbnail)
try fileManager.moveItem(at: export.url, to: thumbnail)
// Configure with the new URL
let thumbnailExport = MediaExport(url: thumbnail,
fileSize: export.fileSize,
width: export.width,
height: export.height,
duration: nil)
// And return.
onCompletion(identifier, thumbnailExport)
} catch {
onError(exporterErrorWith(error: error))
}
}
}
| gpl-2.0 |
Roommate-App/roomy | roomy/Pods/Starscream/Sources/WebSocket.swift | 2 | 54234 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// 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 CoreFoundation
import SSCommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public enum ErrorType: Error {
case outputStreamWriteError //output stream error during write
case compressionError
case invalidSSLError //Invalid SSL certificate
case writeTimeoutError //The socket timed out waiting to be ready to write
case protocolError //There was an error parsing the WebSocket frames
case upgradeError //There was an error during the HTTP upgrade
case closeError //There was an error during the close (socket probably has been dereferenced)
}
public struct WSError: Error {
public let type: ErrorType
public let message: String
public let code: Int
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set }
var disableSSLCertValidation: Bool { get set }
var overrideTrustHostname: Bool { get set }
var desiredTrustHostname: String? { get set }
#if os(Linux)
#else
var security: SSLTrustValidator? { get set }
var enabledSSLCipherSuites: [SSLCipherSuite]? { get set }
#endif
var isConnected: Bool { get }
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
let useSSL: Bool
let disableCertValidation: Bool
var overrideTrustHostname: Bool
var desiredTrustHostname: String?
#if os(Linux)
#else
let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
weak var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn)))
}
if resOut != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
} else if self == nil {
completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0))
return
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
let trust = outputStream!.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream!.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
connectedMutex.lock()
let isConnected = connected
connectedMutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let connectedMutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private let readyToWriteMutex = NSLock()
private var canDispatch: Bool {
readyToWriteMutex.lock()
let canWork = readyToWrite
readyToWriteMutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)"
request.setValue(hostValue, forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname)
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let s = self else {return}
if error != nil {
s.disconnectStream(error)
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let s = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
s.certValidated = false
#else
if let sec = s.security, !s.certValidated {
let trustObj = s.stream.sslTrust()
if let possibleTrust = trustObj.trust {
s.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
s.certValidated = false
}
if !s.certValidated {
s.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0))
return
}
}
#endif
let _ = s.stream.write(data: data)
}
s.writeQueue.addOperation(operation)
})
self.readyToWriteMutex.lock()
self.readyToWrite = true
self.readyToWriteMutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
connectedMutex.lock()
connected = false
connectedMutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
connectedMutex.lock()
connected = true
connectedMutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.advancedDelegate?.websocketDidConnect(socket: s)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
s.onPong?(pongData)
s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str)
s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = s.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor {
do {
data = try compressor.compress(data)
if s.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= s.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
if !s.readyToWrite {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
}
let stream = s.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
connectedMutex.lock()
connected = false
connectedMutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
readyToWriteMutex.lock()
readyToWrite = false
readyToWriteMutex.unlock()
cleanupStream()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
#if swift(>=4)
#else
fileprivate extension String {
var count: Int {
return self.characters.count
}
}
#endif
| mit |
Cleverlance/Pyramid | Example/Tests/Scope Management/Application/InstanceProviderImplTests.swift | 1 | 1303 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
import XCTest
import Nimble
import Pyramid
class InstanceProviderImplTests: XCTestCase {
func test_ItConformsToInstanceProvider() {
let _: InstanceProvider<Int>? = (nil as InstanceProviderImpl<Int>?)
}
func test_ItDependsOnScopeController() {
let _ = InstanceProviderImpl<Int>(scopeController: ScopeControllerDummy())
}
func test_GetInstance_ItShouldReturnInstanceFromScopeFromGivenController() {
let provider = InstanceProviderImpl<Int>(
scopeController: ScopeControllerWithScopeReturning42()
)
let result = provider.getInstance()
expect(result) == 42
}
}
private class ScopeControllerDummy: ScopeController {
let isScopeLoaded = false
func discardScope() {}
func getScope() -> Scope { return ScopeDummy(parent: nil) }
}
private class ScopeControllerWithScopeReturning42: ScopeController {
let isScopeLoaded = false
func discardScope() {}
func getScope() -> Scope {
return ScopeReturning42(parent: nil)
}
}
private class ScopeReturning42: Scope {
required init(parent: Scope?) {}
func getInstance<T>(of type: T.Type) -> T? {
if let result = 42 as? T { return result }
return nil
}
}
| mit |
narner/AudioKit | Examples/iOS/Drums/Drums/AppDelegate.swift | 1 | 2170 | //
// AppDelegate.swift
// Drums
//
// Created by Aurelius Prochazka on 8/13/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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 |
GermanCentralLibraryForTheBlind/LargePrintMusicNotes | LargePrintMusicNotesViewer/PdfViewerController.swift | 1 | 2561 | // Created by Lars Voigt.
//
//The MIT License (MIT)
//Copyright (c) 2016 German Central Library for the Blind (DZB)
//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
class PdfViewerController: UIViewController {
@IBOutlet weak var webView: UIWebView!
var composition = [String:AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// if let pdf = NSBundle.mainBundle().URLForResource("example", withExtension: "pdf", subdirectory: nil, localization: nil) {
// let req = NSURLRequest(URL: pdf)
// self.webView.loadRequest(req)
// }
self.navigationItem.title = composition["title"] as? String
let url = "http://dacapolp.dzb.de:13857/DaCapoLP/show/?id=" + String((composition["id"] as? Int)!)
self.webView.loadRequest(URLRequest(url: URL(string: url)!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setCurrentComposition(_ compo: [String:AnyObject]) {
composition = compo
}
/*
// 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.
}
*/
}
| mit |
lenssss/whereAmI | Whereami/Controller/Personal/PublishTourPhotoCollectionTableViewCell.swift | 1 | 4600 | //
// PublishTourPhotoCollectionTableViewCell.swift
// Whereami
//
// Created by A on 16/4/28.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
//import TZImagePickerController
class PublishTourPhotoCollectionTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
var collectionView:UICollectionView? = nil
var photoArray:[AnyObject]? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setupUI(){
self.backgroundColor = UIColor.clearColor()
let flowLayout = UICollectionViewFlowLayout()
self.collectionView = UICollectionView(frame: self.contentView.bounds,collectionViewLayout: flowLayout)
self.collectionView?.backgroundColor = UIColor.clearColor()
self.collectionView?.dataSource = self
self.collectionView?.delegate = self
self.collectionView?.scrollEnabled = false
self.contentView.addSubview(self.collectionView!)
self.collectionView?.registerClass(PersonalPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PersonalPhotoCollectionViewCell")
self.collectionView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0))
}
func updateCollections(){
self.collectionView?.reloadData()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let photos = self.photoArray else {
return 0
}
if(photos.count == 9 ) {
return 9
}
else {
return photos.count+1
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PersonalPhotoCollectionViewCell", forIndexPath: indexPath) as! PersonalPhotoCollectionViewCell
if indexPath.row == self.photoArray?.count {
cell.photoView?.image = UIImage(named: "plus")
}
else{
// if self.photoArray![indexPath.row].isKindOfClass(UIImage) {
// let image = self.photoArray![indexPath.row] as! UIImage
// cell.photoView?.image = image
// }
// else{
// TZImageManager().getPhotoWithAsset(self.photoArray![indexPath.row], completion: { (image, dic, bool) in
// cell.photoView?.image = image
// })
// }
cell.photoView?.image = self.photoArray![indexPath.row] as? UIImage
}
// cell.photoView?.image = self.photoArray![indexPath.row] as? UIImage
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(8, 16, 8, 16)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 8
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{
return 8
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenW = UIScreen.mainScreen().bounds.width
let photoWidth = (screenW-16*2-8*3)/4
let size = CGSize(width: photoWidth,height: photoWidth)
return size
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == self.photoArray?.count {
NSNotificationCenter.defaultCenter().postNotificationName("didTouchAddButton", object: collectionView)
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
GermanCentralLibraryForTheBlind/LargePrintMusicNotes | LargePrintMusicNotesViewer/RESTConnector.swift | 1 | 5168 | // Created by Lars Voigt.
//
//The MIT License (MIT)
//Copyright (c) 2016 German Central Library for the Blind (DZB)
//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 Alamofire
import SwiftyJSON
class RESTConnector {
//let endpoint = "http://musiclargeprint-tttttest.rhcloud.com/"
let endpoint = "http://dacapolp.dzb.de:13857/DaCapoLP/"
let login = "login/"
let list = "list/"
let show = "show/"
func getUserData(_ userName : String, password : String, completionHandler: @escaping ([[String:AnyObject]], String?) -> Void) {
var parameters: [String:Any] = [:]
Alamofire.request(self.endpoint + self.login, method: .get, parameters: parameters).responseJSON {
response in
switch response.result {
case .success:
if let JSON = response.result.value {
// print("Did receive JSON data: \(JSON)")
let jsonData = JSON as! [String:Any]
let csrf_token = jsonData["csrf_token"] as! String;
parameters = ["username" : userName, "password" : password , "csrfmiddlewaretoken" : csrf_token]
} else {
completionHandler([[String:AnyObject]](), "JSON(csrf_token) data is nil.");
}
Alamofire.request(self.endpoint + self.login, method: .post, parameters: parameters).responseJSON {
response in
switch response.result {
case .success:
Alamofire.request(self.endpoint + self.list, method: .get).responseJSON {
response in
switch response.result {
case .success(let value):
if let resData = JSON(value)["files"].arrayObject {
completionHandler(resData as! [[String:AnyObject]], nil)
}
break
case .failure:
completionHandler([[String:AnyObject]](), self.getErrorMessage(response))
break
}
}
break
case .failure:
completionHandler([[String:AnyObject]](), self.getErrorMessage(response))
break
}
}
case .failure:
completionHandler([[String:AnyObject]](), self.getErrorMessage(response))
break
}
}
}
func getErrorMessage(_ response: Alamofire.DataResponse<Any>) -> String {
let message : String
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 400:
message = "Nutzername oder Passwort nicht vorhanden."
case 401:
message = "Der eingegebene Nutzername und/oder das Passwort ist nicht gültig."
case 404:
message = "Der gewünschte Service steht zur Zeit nicht zur Verfügung."
case 500:
message = "Der Service arbeitet fehlerhaft, bitte kontaktieren Sie einen DZB-Mitarbieter."
case 503:
message = "Der Service ist nicht verfügbar, bitte kontaktieren Sie einen DZB-Mitarbieter."
default:
message = "Status Code: " + String(httpStatusCode);
}
} else {
message = response.result.error!.localizedDescription;
}
// print("error: " + message);
return message;
}
}
| mit |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Engine/Consume.swift | 1 | 1521 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
var checkComments = true
extension Engine {
func makeProcessor(
input: String, bounds: Range<String.Index>, matchMode: MatchMode
) -> Processor {
Processor(
program: program,
input: input,
subjectBounds: bounds,
searchBounds: bounds,
matchMode: matchMode,
isTracingEnabled: enableTracing,
shouldMeasureMetrics: enableMetrics)
}
func makeFirstMatchProcessor(
input: String,
subjectBounds: Range<String.Index>,
searchBounds: Range<String.Index>
) -> Processor {
Processor(
program: program,
input: input,
subjectBounds: subjectBounds,
searchBounds: searchBounds,
matchMode: .partialFromFront,
isTracingEnabled: enableTracing,
shouldMeasureMetrics: enableMetrics)
}
}
extension Processor {
// TODO: Should we throw here?
mutating func consume() -> Input.Index? {
while true {
switch self.state {
case .accept:
return self.currentPosition
case .fail:
return nil
case .inProgress: self.cycle()
}
}
}
}
| apache-2.0 |
bsmith11/ScoreReporter | ScoreReporterCore/ScoreReporterCore/View Models/GameViewModel.swift | 1 | 2366 | //
// GameViewModel.swift
// ScoreReporter
//
// Created by Bradley Smith on 9/25/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import UIKit
public enum GameViewState {
case full
case normal
case minimal
}
public struct GameViewModel {
public let game: Game?
public let startDate: String?
public let homeTeamName: NSAttributedString
public let homeTeamScore: NSAttributedString?
public let awayTeamName: NSAttributedString
public let awayTeamScore: NSAttributedString?
public let fieldName: String
public let status: String?
public let state: GameViewState
fileprivate let winnerAttributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightBlack)
]
fileprivate let loserAttributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightThin)
]
public init(game: Game?, state: GameViewState = .normal ) {
self.game = game
let dateFormatter = DateService.gameStartDateFullFormatter
startDate = game?.startDateFull.flatMap { dateFormatter.string(from: $0) }
var homeAttributes = loserAttributes
var awayAttributes = loserAttributes
let homeScore = game?.homeTeamScore ?? ""
let awayScore = game?.awayTeamScore ?? ""
if let status = game?.status, status == "Final" {
let score1 = Int(homeScore) ?? 0
let score2 = Int(awayScore) ?? 0
if score1 > score2 {
homeAttributes = winnerAttributes
awayAttributes = loserAttributes
}
else {
homeAttributes = loserAttributes
awayAttributes = winnerAttributes
}
}
let homeName = game?.homeTeamName ?? "TBD"
homeTeamName = NSAttributedString(string: homeName, attributes: homeAttributes)
homeTeamScore = NSAttributedString(string: homeScore, attributes: homeAttributes)
let awayName = game?.awayTeamName ?? "TBD"
awayTeamName = NSAttributedString(string: awayName, attributes: awayAttributes)
awayTeamScore = NSAttributedString(string: awayScore, attributes: awayAttributes)
fieldName = game?.fieldName ?? "TBD"
status = game?.status
self.state = state
}
}
| mit |
kenshin03/Cherry | Cherry/Shared/Utils/KTActivityManager.swift | 5 | 8784 | //
// KTActivityManager.swift
// Cherry
//
// Created by Kenny Tang on 2/22/15.
//
//
import UIKit
protocol KTActivityManagerDelegate {
func activityManager(manager:KTActivityManager?, activityDidUpdate model:KTPomodoroActivityModel?)
func activityManager(manager:KTActivityManager?, activityDidPauseForBreak elapsedBreakTime:Int)
}
class KTActivityManager {
// MARK: - Properties
var activity:KTPomodoroActivityModel?
var activityTimer:NSTimer?
var breakTimer:NSTimer?
var currentPomo:Int?
var breakElapsed:Int?
var delegate:KTActivityManagerDelegate?
// MARK: - Public
class var sharedInstance: KTActivityManager {
struct Static {
static let instance: KTActivityManager = KTActivityManager()
}
return Static.instance
}
func startActivity(activity:KTPomodoroActivityModel, error:NSErrorPointer) {
if (self.hasOtherActiveActivityInSharedState(activity.activityID)) {
error.memory = NSError(domain:"com.corgitoergosum.net",
code: Constants.KTPomodoroStartActivityError.OtherActivityActive.rawValue,
userInfo: nil)
return
}
// initialize internal variables
self.intializeInternalState(activity)
// start timer
self.startActivityTimer()
}
func continueActivity(activity:KTPomodoroActivityModel) {
self.activity = activity
self.currentPomo = activity.current_pomo.integerValue
self.updateSharedActiveActivityStateFromModel(activity)
self.startActivityTimer()
}
func stopActivity() {
self.activity?.status = Constants.KTPomodoroActivityStatus.Stopped.rawValue
if let activity = self.activity {
self.updateSharedActiveActivityStateFromModel(activity)
}
// save to disk
KTCoreDataStack.sharedInstance.saveContext()
self.resetManagerInternalState()
}
// MARK: - Private
// MARK: startActivity: helper methods
func resetManagerInternalState() {
self.activity = nil
self.currentPomo = 0
self.breakElapsed = 0
self.invalidateTimers()
}
func startActivityTimer () {
self.invalidateTimers()
self.activityTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("activityTimerFired"), userInfo: nil, repeats: true)
self.scheduleTimerInRunLoop(self.activityTimer!)
}
func intializeInternalState(activity:KTPomodoroActivityModel) {
self.currentPomo = 1;
self.breakElapsed = 0;
activity.current_pomo = 0;
activity.current_pomo_elapsed_time = 0
activity.status = Constants.KTPomodoroActivityStatus.InProgress.rawValue;
self.activity = activity;
self.updateSharedActiveActivityStateFromModel(activity)
}
func hasOtherActiveActivityInSharedState(ID:String) -> Bool {
if let activity = self.activeActivityInSharedStorage() as KTActiveActivityState? {
return activity.activityID != ID
}
return false
}
func activeActivityInSharedStorage() -> KTActiveActivityState? {
if let activityData = KTSharedUserDefaults.sharedUserDefaults.objectForKey("ActiveActivity") as? NSData {
if let activity = NSKeyedUnarchiver.unarchiveObjectWithData(activityData) as? KTActiveActivityState{
return activity
}
}
return nil
}
func updateSharedActiveActivityStateFromModel(activeActivity:KTPomodoroActivityModel) {
var updatedActiveActivity:KTActiveActivityState
if let sharedActivity = self.activeActivityInSharedStorage(){
if (sharedActivity.activityID == activeActivity.activityID) {
// update existing object
updatedActiveActivity = sharedActivity
updatedActiveActivity.currentPomo = activeActivity.current_pomo.integerValue
updatedActiveActivity.status = activeActivity.status.integerValue
updatedActiveActivity.elapsedSecs = activeActivity.current_pomo_elapsed_time.integerValue
} else {
updatedActiveActivity = self.createActiveActivityFromModel(activeActivity)
}
} else {
//creaate new object the first time
updatedActiveActivity = self.createActiveActivityFromModel(activeActivity)
}
if (updatedActiveActivity.status == Constants.KTPomodoroActivityStatus.Stopped.rawValue) {
KTSharedUserDefaults.sharedUserDefaults.removeObjectForKey("ActiveActivity")
} else {
let encodedActivity:NSData = NSKeyedArchiver.archivedDataWithRootObject(updatedActiveActivity);
KTSharedUserDefaults.sharedUserDefaults.setObject(encodedActivity, forKey: "ActiveActivity")
}
KTSharedUserDefaults.sharedUserDefaults.synchronize()
}
func createActiveActivityFromModel(activeActivity:KTPomodoroActivityModel) -> KTActiveActivityState {
return KTActiveActivityState(id: activeActivity.activityID,
name: activeActivity.name,
status: activeActivity.status.integerValue,
currentPomo: activeActivity.current_pomo.integerValue,
elapsed: activeActivity.current_pomo_elapsed_time.integerValue)
}
func invalidateTimers() {
self.activityTimer?.invalidate()
self.breakTimer?.invalidate()
}
func scheduleTimerInRunLoop(timer:NSTimer) {
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
// MARK - timers helper methods
@objc func activityTimerFired() {
// increment current pomo elapsed time
self.activity?.current_pomo = self.currentPomo!;
var currentPomoElapsed = 0
if let elapsed = self.activity?.current_pomo_elapsed_time.integerValue {
currentPomoElapsed = elapsed + 1
self.activity?.current_pomo_elapsed_time = currentPomoElapsed
}
self.delegate?.activityManager(self, activityDidUpdate: self.activity)
if let activity = self.activity {
self.updateSharedActiveActivityStateFromModel(activity)
}
if (currentPomoElapsed == KTSharedUserDefaults.pomoDuration*60) {
// reached end of pomo
self.handlePomoEnded()
}
}
// Swift Gotchas
@objc func breakTimerFired() {
self.breakElapsed!++
if (self.breakElapsed < KTSharedUserDefaults.breakDuration*60) {
self.delegate?.activityManager(self, activityDidPauseForBreak: self.breakElapsed!)
} else {
self.invalidateTimers()
self.breakElapsed = 0
self.startNextPomo()
}
}
// MARK: breakTimerFired: helper methods
func startNextPomo() {
println("starting next pomo")
self.activity?.current_pomo = self.currentPomo!;
self.activity?.current_pomo_elapsed_time = 0;
// restart the timer
self.activityTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("activityTimerFired"), userInfo: nil, repeats: true)
self.scheduleTimerInRunLoop(self.activityTimer!)
}
// MARK: activityTimerFired: helper methods
func handlePomoEnded() {
if (self.activityHasMorePomo(self.activity)) {
self.currentPomo!++
self.activity?.current_pomo = self.currentPomo!
self.pauseActivityStartBreak()
} else {
self.completeActivityOnLastPomo()
}
}
// MARK: handlePomoEnded helper methods
func completeActivityOnLastPomo() {
self.activity?.status = Constants.KTPomodoroActivityStatus.Completed.rawValue
self.activity?.actual_pomo = self.currentPomo!
// save to disk
KTCoreDataStack.sharedInstance.saveContext()
self.delegate?.activityManager(self, activityDidUpdate: self.activity)
self.resetManagerInternalState()
}
func pauseActivityStartBreak() {
self.activityTimer?.invalidate()
self.startBreakTimer()
}
func startBreakTimer() {
println("starting break")
self.breakTimer?.invalidate()
self.breakTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("breakTimerFired"), userInfo: nil, repeats: true)
self.scheduleTimerInRunLoop(self.breakTimer!)
}
func activityHasMorePomo(activity:KTPomodoroActivityModel?) -> Bool{
if let activity = activity {
let expectedPomo = activity.expected_pomo.integerValue
if let currentPomo = self.currentPomo {
return expectedPomo > currentPomo
}
}
return false
}
}
| mit |
czechboy0/swift-package-crawler | Sources/DataUpdater/main.swift | 1 | 361 |
import Utils
import Foundation
import Tasks
//in Cache folder, git add everything, commit with the timestamp, push to remote
do {
print("DataUpdater starting")
defer { print("DataUpdater finished") }
let cacheRoot = try cacheRootPath()
try ifChangesCommitAndPush(repoPath: try cacheRootPath())
} catch {
print(error)
exit(1)
}
| mit |
apple/swift-package-manager | Sources/PackageModel/Snippets/Model/Snippet.swift | 2 | 1197 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 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
//
//===----------------------------------------------------------------------===//
import TSCBasic
public struct Snippet {
public var path: AbsolutePath
public var explanation: String
public var presentationCode: String
public var groupName: String? = nil
public var name: String {
path.basenameWithoutExt
}
init(parsing source: String, path: AbsolutePath) {
let extractor = PlainTextSnippetExtractor(source: source)
self.path = path
self.explanation = extractor.explanation
self.presentationCode = extractor.presentationCode
}
public init(parsing file: AbsolutePath) throws {
let source = try String(contentsOf: file.asURL)
self.init(parsing: source, path: file)
}
}
| apache-2.0 |
balthild/Mathemalpha | Mathemalpha/SchemesView.swift | 1 | 1120 | //
// TypesView.swift
// Mathemalpha
//
// Created by Balthild Ires on 18/09/2017.
// Copyright © 2017 Balthild Ires. All rights reserved.
//
import Cocoa
class SchemesView: NSView {
var selected = 0
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
var y: CGFloat = 0
for (i, type) in Schemes.schemeNames.enumerated() {
let rect = NSMakeRect(0, y, 140, 24)
let marginTop = (24 - type.size(withAttributes: Styles.schemesTextAttributes).height) / 2
let textRect = NSMakeRect(10, y + marginTop, 120, 24 - marginTop)
if i == selected {
let path = NSBezierPath(roundedRect: rect, xRadius: 4, yRadius: 4)
Styles.schemesTileColor.set()
path.fill()
type.draw(in: textRect, withAttributes: Styles.schemesSelectedTextAttributes)
} else {
type.draw(in: textRect, withAttributes: Styles.schemesTextAttributes)
}
y += 24
}
}
override var isFlipped: Bool {
return true
}
}
| gpl-3.0 |
apple/swift-async-algorithms | Sources/AsyncAlgorithms/AsyncChannel.swift | 1 | 8882 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@preconcurrency @_implementationOnly import OrderedCollections
/// A channel for sending elements from one task to another with back pressure.
///
/// The `AsyncChannel` class is intended to be used as a communication type between tasks,
/// particularly when one task produces values and another task consumes those values. The back
/// pressure applied by `send(_:)` via the suspension/resume ensures that
/// the production of values does not exceed the consumption of values from iteration. This method
/// suspends after enqueuing the event and is resumed when the next call to `next()`
/// on the `Iterator` is made, or when `finish()` is called from another Task.
/// As `finish()` induces a terminal state, there is no need for a back pressure management.
/// This function does not suspend and will finish all the pending iterations.
public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
/// The iterator for a `AsyncChannel` instance.
public struct Iterator: AsyncIteratorProtocol, Sendable {
let channel: AsyncChannel<Element>
var active: Bool = true
init(_ channel: AsyncChannel<Element>) {
self.channel = channel
}
/// Await the next sent element or finish.
public mutating func next() async -> Element? {
guard active else {
return nil
}
let generation = channel.establish()
let nextTokenStatus = ManagedCriticalState<ChannelTokenStatus>(.new)
let value = await withTaskCancellationHandler {
await channel.next(nextTokenStatus, generation)
} onCancel: { [channel] in
channel.cancelNext(nextTokenStatus, generation)
}
if let value {
return value
} else {
active = false
return nil
}
}
}
typealias Pending = ChannelToken<UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>>
typealias Awaiting = ChannelToken<UnsafeContinuation<Element?, Never>>
struct ChannelToken<Continuation: Sendable>: Hashable, Sendable {
var generation: Int
var continuation: Continuation?
init(generation: Int, continuation: Continuation) {
self.generation = generation
self.continuation = continuation
}
init(placeholder generation: Int) {
self.generation = generation
self.continuation = nil
}
func hash(into hasher: inout Hasher) {
hasher.combine(generation)
}
static func == (_ lhs: ChannelToken, _ rhs: ChannelToken) -> Bool {
return lhs.generation == rhs.generation
}
}
enum ChannelTokenStatus: Equatable {
case new
case cancelled
}
enum Emission : Sendable {
case idle
case pending(OrderedSet<Pending>)
case awaiting(OrderedSet<Awaiting>)
case finished
}
struct State : Sendable {
var emission: Emission = .idle
var generation = 0
}
let state = ManagedCriticalState(State())
/// Create a new `AsyncChannel` given an element type.
public init(element elementType: Element.Type = Element.self) { }
func establish() -> Int {
state.withCriticalRegion { state in
defer { state.generation &+= 1 }
return state.generation
}
}
func cancelNext(_ nextTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) {
state.withCriticalRegion { state in
let continuation: UnsafeContinuation<Element?, Never>?
switch state.emission {
case .awaiting(var nexts):
continuation = nexts.remove(Awaiting(placeholder: generation))?.continuation
if nexts.isEmpty {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
default:
continuation = nil
}
nextTokenStatus.withCriticalRegion { status in
if status == .new {
status = .cancelled
}
}
continuation?.resume(returning: nil)
}
}
func next(_ nextTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) async -> Element? {
return await withUnsafeContinuation { (continuation: UnsafeContinuation<Element?, Never>) in
var cancelled = false
var terminal = false
state.withCriticalRegion { state in
if nextTokenStatus.withCriticalRegion({ $0 }) == .cancelled {
cancelled = true
}
switch state.emission {
case .idle:
state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)])
case .pending(var sends):
let send = sends.removeFirst()
if sends.count == 0 {
state.emission = .idle
} else {
state.emission = .pending(sends)
}
send.continuation?.resume(returning: continuation)
case .awaiting(var nexts):
nexts.updateOrAppend(Awaiting(generation: generation, continuation: continuation))
state.emission = .awaiting(nexts)
case .finished:
terminal = true
}
}
if cancelled || terminal {
continuation.resume(returning: nil)
}
}
}
func cancelSend(_ sendTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) {
state.withCriticalRegion { state in
let continuation: UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>?
switch state.emission {
case .pending(var sends):
let send = sends.remove(Pending(placeholder: generation))
if sends.isEmpty {
state.emission = .idle
} else {
state.emission = .pending(sends)
}
continuation = send?.continuation
default:
continuation = nil
}
sendTokenStatus.withCriticalRegion { status in
if status == .new {
status = .cancelled
}
}
continuation?.resume(returning: nil)
}
}
func send(_ sendTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int, _ element: Element) async {
let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in
state.withCriticalRegion { state in
if sendTokenStatus.withCriticalRegion({ $0 }) == .cancelled {
continuation.resume(returning: nil)
return
}
switch state.emission {
case .idle:
state.emission = .pending([Pending(generation: generation, continuation: continuation)])
case .pending(var sends):
sends.updateOrAppend(Pending(generation: generation, continuation: continuation))
state.emission = .pending(sends)
case .awaiting(var nexts):
let next = nexts.removeFirst().continuation
if nexts.count == 0 {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
continuation.resume(returning: next)
case .finished:
continuation.resume(returning: nil)
}
}
}
continuation?.resume(returning: element)
}
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made
/// or when a call to `finish()` is made from another Task.
/// If the channel is already finished then this returns immediately
/// If the task is cancelled, this function will resume. Other sending operations from other tasks will remain active.
public func send(_ element: Element) async {
let generation = establish()
let sendTokenStatus = ManagedCriticalState<ChannelTokenStatus>(.new)
await withTaskCancellationHandler {
await send(sendTokenStatus, generation, element)
} onCancel: { [weak self] in
self?.cancelSend(sendTokenStatus, generation)
}
}
/// Send a finish to all awaiting iterations.
/// All subsequent calls to `next(_:)` will resume immediately.
public func finish() {
state.withCriticalRegion { state in
defer { state.emission = .finished }
switch state.emission {
case .pending(let sends):
for send in sends {
send.continuation?.resume(returning: nil)
}
case .awaiting(let nexts):
for next in nexts {
next.continuation?.resume(returning: nil)
}
default:
break
}
}
}
/// Create an `Iterator` for iteration of an `AsyncChannel`
public func makeAsyncIterator() -> Iterator {
return Iterator(self)
}
}
| apache-2.0 |
kbelter/SnazzyList | SnazzyList/Classes/src/TableView/Protocols/GenericTableCellSelfSizingProtocol.swift | 1 | 311 | //
// TableView.swift
// Noteworth2
//
// Created by Kevin on 12/20/18.
// Copyright © 2018 Noteworth. All rights reserved.
//
import UIKit
public protocol GenericTableCellSelfSizingProtocol {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath, with item: Any) -> CGFloat
}
| apache-2.0 |
eduardoeof/Gollum | Gollum/dao/VersionDAOProtocol.swift | 1 | 388 | //
// VersionDAOProtocol.swift
// Gollum
//
// Created by eduardo.ferreira on 6/1/16.
// Copyright © 2016 eduardoeof. All rights reserved.
//
import Foundation
protocol VersionDAOProtocol {
func saveSelectedVersion(_ version: Version, testName name: String)
func didSelectVersionForTest(_ name: String) -> Bool
func loadSelectedVersions() throws -> [String: Version]
}
| mit |
coderMONSTER/ioscelebrity | YStar/YStar/Scenes/Controller/SetPayPwdVC.swift | 1 | 7655 | //
// SetPayPwdVC.swift
// YStar
//
// Created by MONSTER on 2017/7/18.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class SetPayPwdVC: BaseTableViewController,UITextFieldDelegate {
var setPass = false
var showKeyBoard : Bool = false
var passString : String = ""
// 下一步按钮
@IBOutlet weak var doSetPwdButton: UIButton!
fileprivate var pwdCircleArr = [UILabel]()
fileprivate var textField:UITextField!
// MARK: - 初始化
override func viewDidLoad() {
super.viewDidLoad()
initUI()
setupUI()
}
func initUI() {
doSetPwdButton.setTitle(setPass == false ? "下一步" :"确定", for: .normal)
self.title = setPass == true ? "请确认交易密码" : "设置交易密码"
self.doSetPwdButton.backgroundColor = UIColor.gray
}
func setupUI() {
textField = UITextField(frame: CGRect(x: 0,y: 60, width: view.frame.size.width, height: 35))
textField.delegate = self
textField.isHidden = true
textField.keyboardType = UIKeyboardType.numberPad
view.addSubview(textField!)
textField.backgroundColor = UIColor.red
textField.becomeFirstResponder()
for i in 0 ..< 6 {
let line:UIView = UIView(frame: CGRect(x: 30 + CGFloat(i) * 10 + (( kScreenWidth - 110) / 6.0) * CGFloat(i),
y: 120,
width: ((kScreenWidth - 110) / 6.0) ,
height: ((kScreenWidth - 110) / 6.0)))
line.backgroundColor = UIColor.clear
line.alpha = 1
line.layer.borderWidth = 1
line.layer.cornerRadius = 3
line.layer.borderColor = UIColor.gray.cgColor
view.addSubview(line)
let circleLabel:UILabel = UILabel(frame: CGRect(x: 0 ,
y: 0 ,
width: ((kScreenWidth - 110) / 6.0),
height: ((kScreenWidth - 110) / 6.0)))
circleLabel.textAlignment = .center
circleLabel.text = "﹡"
circleLabel.font = UIFont.systemFont(ofSize: 17)
circleLabel.layer.masksToBounds = true
circleLabel.isHidden = true
pwdCircleArr.append(circleLabel)
line.addSubview(circleLabel)
}
let btn = UIButton.init(type: .custom)
btn.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 150)
btn.addTarget(self, action: #selector(showKeyBordButtonAction(_:)), for: .touchUpInside)
view.addSubview(btn)
}
// MARK: - 显示键盘
@IBAction func showKeyBordButtonAction(_ sender: UIButton) {
if showKeyBoard == true {
textField.resignFirstResponder()
} else {
textField.becomeFirstResponder()
}
showKeyBoard = !showKeyBoard
}
// MARK: - 下一步按钮
@IBAction func doSetPwdButtonAction(_ sender: UIButton) {
let phoneNum = UserDefaults.standard.value(forKey: AppConst.UserDefaultKey.phone.rawValue) as! String
// 请求接口设置交易密码
if setPass == true {
if passString.length() == 6 {
if ShareModelHelper.instance().setPayPwd["passString"] != passString {
SVProgressHUD.showErrorMessage(ErrorMessage: "两次密码输入不一致", ForDuration: 2.0, completion: {})
return
}
}
let model = ResetPayPwdRequestModel()
model.phone = phoneNum
model.pwd = passString.md5()
model.timestamp = 1
model.type = 0
AppAPIHelper.commen().ResetPayPwd(requestModel: model, complete: { (response) -> ()? in
if let objects = response as? ResultModel {
if objects.result == 0 {
SVProgressHUD.showSuccessMessage(SuccessMessage: "设置成功", ForDuration: 2.0, completion: {
let vcCount = self.navigationController?.viewControllers.count
_ = self.navigationController?.popToViewController((self.navigationController?.viewControllers[vcCount! - 3])!, animated: true)
})
}
} else {
SVProgressHUD.showErrorMessage(ErrorMessage: "设置失败", ForDuration: 2.0, completion: nil)
}
return nil
}, error: { (error) -> ()? in
self.didRequestError(error)
return nil
})
} else {
if passString.length() == 6 {
let setPayPwdVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "SetPayPwdVC") as! SetPayPwdVC
setPayPwdVC.setPass = true
ShareModelHelper.instance().setPayPwd["passString"] = passString
self.navigationController?.pushViewController(setPayPwdVC, animated: true)
} else {
SVProgressHUD.showErrorMessage(ErrorMessage: "密码需要6位", ForDuration: 2.0, completion: {})
}
}
}
// MARK: - 输入变成点
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(textField.text?.characters.count > 5 && string.characters.count > 0) {
return false
}
var password : String
if string.characters.count <= 0 && textField.text?.length() != 0 {
let index = textField.text?.characters.index((textField.text?.endIndex)!, offsetBy: -1)
password = textField.text!.substring(to: index!)
}
else {
password = textField.text! + string
}
passString = ""
self.doSetPwdButton.backgroundColor = UIColor.gray
self.setCircleShow(password.characters.count)
if(password.characters.count == 6) {
passString = password
self.doSetPwdButton.backgroundColor = UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue)
}
return true;
}
func setCircleShow(_ count:NSInteger) {
for circle in pwdCircleArr {
let supView = circle.superview
supView?.layer.borderColor = UIColor.gray.cgColor
supView?.layer.borderWidth = 1
circle.isHidden = true;
}
for i in 0 ..< count {
pwdCircleArr[i].isHidden = false
let view = pwdCircleArr[i]
let supView = view.superview
supView?.layer.borderColor = UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue).cgColor
supView?.layer.borderWidth = 2
}
}
}
| mit |
kz56cd/ios_sandbox_animate | IosSandboxAnimate/CustomParts/BottomShadowButton.swift | 1 | 776 | //
// BottomShadowButton.swift
// e-park
//
// Created by KaiKeima on 2015/12/22.
// Copyright © 2015年 OHAKO,inc. All rights reserved.
//
import UIKit
@IBDesignable class BottomShadowButton: UIButton {
override func drawRect(rect: CGRect) {
self.layer.backgroundColor = self.backgroundColor?.CGColor
self.backgroundColor = UIColor.clearColor()
self.layer.cornerRadius = 4.0
self.layer.shadowColor = self.backgroundColor!.transitionColor(nextColor: UIColor.blackColor(), portion: 0.5).CGColor
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 0.0
self.layer.shadowOffset = CGSizeMake(0, 2.0)
// self.clipsToBounds = true
//
super.drawRect(rect)
}
}
| mit |
ashikahmad/SugarAnchor | Example/Tests/ActiveLessEqualConstraintsTests.swift | 1 | 3814 | //
// ActiveLessEqualConstraintsTests.swift
// SugarAnchor
//
// Created by Ashik uddin Ahmad on 5/14/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import XCTest
import SugarAnchor
class ActiveLessEqualConstraintsTests: XCTestCase {
var containerView: UIView!
var view1: UIView!
var view2: UIView!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
containerView = UIView()
view1 = UIView()
view2 = UIView()
view1.translatesAutoresizingMaskIntoConstraints = false
view2.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(view1)
containerView.addSubview(view2)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
containerView = nil
view1 = nil
view2 = nil
super.tearDown()
}
func testBasic() {
let constraint = view1.leadingAnchor <*= view2.leadingAnchor
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.secondItem === view2)
XCTAssert(constraint.firstAttribute == .leading)
XCTAssert(constraint.secondAttribute == .leading)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.isActive == true)
}
func testWithConstant() {
let constraint = view1.leadingAnchor <*= view2.leadingAnchor + 20
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.secondItem === view2)
XCTAssert(constraint.firstAttribute == .leading)
XCTAssert(constraint.secondAttribute == .leading)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.constant == 20)
XCTAssert(constraint.isActive == true)
}
func testWithNegativeConstant() {
let constraint = view1.leadingAnchor <*= view2.leadingAnchor - 20
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.secondItem === view2)
XCTAssert(constraint.firstAttribute == .leading)
XCTAssert(constraint.secondAttribute == .leading)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.constant == -20)
XCTAssert(constraint.isActive == true)
}
func testConstantOnly() {
let constraint = view1.widthAnchor <*= 200
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.firstAttribute == .width)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.constant == 200)
XCTAssert(constraint.isActive == true)
}
func testWithMultiplier() {
let constraint = view1.widthAnchor <*= view2.widthAnchor * 2
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.secondItem === view2)
XCTAssert(constraint.firstAttribute == .width)
XCTAssert(constraint.secondAttribute == .width)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.multiplier == 2)
XCTAssert(constraint.isActive == true)
}
func testWithMultiplierAndConstant() {
let constraint = view1.widthAnchor <*= view2.widthAnchor * 2 + 20
XCTAssert(constraint.firstItem === view1)
XCTAssert(constraint.secondItem === view2)
XCTAssert(constraint.firstAttribute == .width)
XCTAssert(constraint.secondAttribute == .width)
XCTAssert(constraint.relation == .lessThanOrEqual)
XCTAssert(constraint.multiplier == 2)
XCTAssert(constraint.constant == 20)
XCTAssert(constraint.isActive == true)
}
}
| mit |
tad-iizuka/swift-sdk | Source/RetrieveAndRankV1/Models/SearchResponse.swift | 3 | 3712 | /**
* Copyright IBM Corporation 2016
*
* 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 RestKit
/** The response received when searching a specific query within the Solr cluster and collection. */
public struct SearchResponse: JSONDecodable {
/// A header containing information about the request and response.
public let header: SearchResponseHeader
/// An object containing the results of the Search request.
public let body: SearchResponseBody
/// Used internally to initialize a `SearchResponse` model from JSON.
public init(json: JSON) throws {
header = try json.decode(at: "responseHeader", type: SearchResponseHeader.self)
body = try json.decode(at: "response", type: SearchResponseBody.self)
}
}
/** An object returned with a Search request, returning more information about the request. */
public struct SearchResponseHeader: JSONDecodable {
/// The status.
public let status: Int
/// The query time.
public let qTime: Int
/// An object containing the parameters that were sent in the request.
public let params: RequestParameters
/// Used internally to initialize a `SearchResponseHeader` model from JSON.
public init(json: JSON) throws {
status = try json.getInt(at: "status")
qTime = try json.getInt(at: "QTime")
params = try json.decode(at: "params", type: RequestParameters.self)
}
}
/** An object containing the query parameters that were sent in the original request. */
public struct RequestParameters: JSONDecodable {
/// The original query string.
public let query: String
/// The return fields the user specified.
public let returnFields: String
/// The writer type.
public let writerType: String
/// Used internally to initialize a `RequestParameters` model from JSON.
public init(json: JSON) throws {
query = try json.getString(at: "q")
returnFields = try json.getString(at: "fl")
writerType = try json.getString(at: "wt")
}
}
/** A named alias for the document results returned by a search function. */
public typealias Document = NSDictionary
/** Contains the results of the Search request. */
public struct SearchResponseBody: JSONDecodable {
/// The number of results found.
public let numFound: Int
/// The index the given results start from.
public let start: Int
/// A list of possible answers whose structure depends on the list of fields the user
/// requested to be returned.
public let documents: [Document]
/// Used internally to initialize a `SearchResponseBody` model from JSON.
public init(json: JSON) throws {
numFound = try json.getInt(at: "numFound")
start = try json.getInt(at: "start")
var docs = [Document]()
let docsJSON = try json.getArray(at: "docs")
for docJSON in docsJSON {
let doc = try JSONSerialization.jsonObject(with: docJSON.serialize(), options: JSONSerialization.ReadingOptions.allowFragments) as! Document
docs.append(doc)
}
documents = docs
}
}
| apache-2.0 |
imitationgame/pokemonpassport | pokepass/View/Create/VCreateFinder.swift | 1 | 5961 | import UIKit
class VCreateFinder:UIView, UITextFieldDelegate
{
weak var controller:CCreate!
weak var field:UITextField!
convenience init(controller:CCreate)
{
self.init()
self.controller = controller
clipsToBounds = true
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
let image:UIImageView = UIImageView()
image.image = UIImage(named:"search")
image.isUserInteractionEnabled = false
image.translatesAutoresizingMaskIntoConstraints = false
image.clipsToBounds = true
image.contentMode = UIViewContentMode.center
let border:UIView = UIView()
border.backgroundColor = UIColor.main
border.isUserInteractionEnabled = false
border.translatesAutoresizingMaskIntoConstraints = false
border.clipsToBounds = true
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(
self,
action:#selector(self.actionButton(sender:)),
for:UIControlEvents.touchUpInside)
let buttonSearch:UIButton = UIButton()
buttonSearch.translatesAutoresizingMaskIntoConstraints = false
buttonSearch.titleLabel?.font = UIFont.bold(size:13)
buttonSearch.setTitleColor(UIColor.main, for:UIControlState())
buttonSearch.setTitleColor(UIColor.main.withAlphaComponent(0.2), for:UIControlState.highlighted)
buttonSearch.setTitle(NSLocalizedString("VCreateFinder_searchButton", comment:""), for:UIControlState())
buttonSearch.addTarget(
self,
action:#selector(self.actionSearch(sender:)),
for:UIControlEvents.touchUpInside)
let field:UITextField = UITextField()
field.keyboardType = UIKeyboardType.alphabet
field.translatesAutoresizingMaskIntoConstraints = false
field.clipsToBounds = true
field.backgroundColor = UIColor.clear
field.borderStyle = UITextBorderStyle.none
field.font = UIFont.medium(size:17)
field.textColor = UIColor.black
field.tintColor = UIColor.black
field.returnKeyType = UIReturnKeyType.search
field.keyboardAppearance = UIKeyboardAppearance.light
field.autocorrectionType = UITextAutocorrectionType.no
field.spellCheckingType = UITextSpellCheckingType.no
field.autocapitalizationType = UITextAutocapitalizationType.words
field.clearButtonMode = UITextFieldViewMode.never
field.placeholder = NSLocalizedString("VCreateFinder_fieldPlaceholder", comment:"")
field.delegate = self
field.clearsOnBeginEditing = true
self.field = field
addSubview(border)
addSubview(image)
addSubview(button)
addSubview(field)
addSubview(buttonSearch)
let views:[String:UIView] = [
"border":border,
"image":image,
"button":button,
"buttonSearch":buttonSearch,
"field":field]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[border]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[button]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:[buttonSearch(70)]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-30-[field(200)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-5-[image(20)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[border(1)]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[image]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[button]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[field]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[buttonSearch]-0-|",
options:[],
metrics:metrics,
views:views))
}
//MARK: actions
func actionButton(sender button:UIButton)
{
field.becomeFirstResponder()
}
func actionSearch(sender button:UIButton)
{
field.resignFirstResponder()
performSearch()
}
//MARK: private
private func performSearch()
{
let text:String = field.text!
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.controller.viewCreate.map.searchLocation(query:text)
}
}
//MARK: field delegate
func textFieldDidBeginEditing(_ textField:UITextField)
{
controller.viewCreate.map.deselectAll()
}
func textFieldShouldReturn(_ textField:UITextField) -> Bool
{
textField.resignFirstResponder()
performSearch()
return true
}
}
| mit |
FuckBoilerplate/RxCache | iOS/Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift | 140 | 3116 | import Foundation
#if _runtime(_ObjC)
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool
public class NMBObjCMatcher : NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
return !matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
return matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
return matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _match(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _doesNotMatch(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
| mit |
practicalswift/swift | validation-test/Reflection/existentials_objc.swift | 2 | 759 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/existentials_objc
// RUN: %target-codesign %t/existentials_objc
// RUN: %target-run %target-swift-reflection-test %t/existentials_objc | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: executable_test
import Foundation
/*
This file pokes at the swift_reflection_projectExistential API
of the SwiftRemoteMirror library.
*/
import SwiftReflectionTest
// Imported class wrapped in AnyObject
// CHECK: Type reference:
// CHECK: (objective_c_class name=NSObject)
reflect(object: NSObject())
// Tagged pointer wrapped in AnyObject
// CHECK: Type reference:
// CHECK: (objective_c_class name=__NSCFNumber)
reflect(object: NSNumber(123))
doneReflecting()
| apache-2.0 |
victor-pavlychko/Encoder | Encoder/EncodableAsIdentity.swift | 1 | 1110 | //
// EncodableAsIdentity.swift
// Encoder
//
// Created by Victor Pavlychko on 12/8/16.
// Copyright © 2016 address.wtf. All rights reserved.
//
import Foundation
public protocol EncodableAsIdentity: Encodable { }
public extension EncodableAsIdentity {
public func encode() -> Encoder {
return Encoder(encodedValue: self)
}
}
extension Bool: EncodableAsIdentity { }
extension Int: EncodableAsIdentity { }
extension Int8: EncodableAsIdentity { }
extension Int16: EncodableAsIdentity { }
extension Int32: EncodableAsIdentity { }
extension Int64: EncodableAsIdentity { }
extension UInt: EncodableAsIdentity { }
extension UInt8: EncodableAsIdentity { }
extension UInt16: EncodableAsIdentity { }
extension UInt32: EncodableAsIdentity { }
extension UInt64: EncodableAsIdentity { }
extension Float: EncodableAsIdentity { }
extension Double: EncodableAsIdentity { }
extension String: EncodableAsIdentity { }
extension StaticString: EncodableAsIdentity { }
extension NSNull: EncodableAsIdentity { }
extension NSNumber: EncodableAsIdentity { }
extension NSString: EncodableAsIdentity { }
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardIssuing/Sources/FeatureCardIssuingDomain/Services/TransactionService.swift | 1 | 626 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import Foundation
final class TransactionService: TransactionServiceAPI {
private let repository: TransactionRepositoryAPI
init(
repository: TransactionRepositoryAPI
) {
self.repository = repository
}
func fetchTransactions(for card: Card?) -> AnyPublisher<[Card.Transaction], NabuNetworkError> {
repository.fetchTransactions(for: card)
}
func fetchMore(for card: Card?) -> AnyPublisher<[Card.Transaction], NabuNetworkError> {
repository.fetchMore(for: card)
}
}
| lgpl-3.0 |
keygx/ButtonStyleKit | ButtonStyleKitSample/ButtonStyleKit/ButtonStyleStandardBase.swift | 1 | 798 | //
// ButtonStyleStandardBase.swift
// ButtonStyleKit
//
// Created by keygx on 2016/08/04.
// Copyright © 2016年 keygx. All rights reserved.
//
import UIKit
open class ButtonStyleStandardBase: ButtonStyleKit {
override public final var isEnabled: Bool {
set {
if newValue {
currentState = .normal
} else {
currentState = .disabled
}
}
get {
return super.isEnabled
}
}
override public final var isHighlighted: Bool {
set {
if newValue {
currentState = .highlighted
} else {
currentState = .normal
}
}
get {
return super.isHighlighted
}
}
}
| mit |
Groupr-Purdue/Groupr-Backend | Sources/Library/Models/Course.swift | 1 | 2373 | import Vapor
import Fluent
import HTTP
public final class Course: Model {
public var id: Node?
public var exists: Bool = false
/// The course's name (i.e. 'CS 408').
public var name: String
/// The course's title (i.e. 'Software Testing').
public var title: String
/// The course's current enrollment (i.e. 40 students).
public var enrollment: Int
/// The designated initializer.
public init(name: String, title: String, enrollment: Int) {
self.id = nil
self.name = name
self.title = title
self.enrollment = enrollment
}
/// Internal: Fluent::Model::init(Node, Context).
public init(node: Node, in context: Context) throws {
self.id = try? node.extract("id")
self.name = try node.extract("name")
self.title = try node.extract("title")
self.enrollment = try node.extract("enrollment")
}
/// Internal: Fluent::Model::makeNode(Context).
public func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name,
"title": title,
"enrollment": enrollment
])
}
/// Establish a many-to-many relationship with User.
public func users() throws -> Siblings<User> {
return try siblings()
}
/// Establish parent-children relation with Group
public func groups() throws -> Children<Group> {
return try children()
}
}
extension Course: Preparation {
/// Create the Course schema when required in the database.
public static func prepare(_ database: Database) throws {
try database.create("courses", closure: { (courses) in
courses.id()
courses.string("name", length: nil, optional: false, unique: true, default: nil)
courses.string("title", length: nil, optional: true, unique: false, default: nil)
courses.int("enrollment", optional: true)
})
}
/// Delete/revert the Course schema when required in the database.
public static func revert(_ database: Database) throws {
try database.delete("courses")
}
}
public extension Request {
public func course() throws -> Course {
guard let json = self.json else {
throw Abort.badRequest
}
return try Course(node: json)
}
}
| mit |
urbn/URBNValidator | URBNValidator.playground/Pages/Object Validation.xcplaygroundpage/Contents.swift | 1 | 1040 | //: [Block Rules](@previous)
/*:
# Object Validation
This is what it's all about. Here we're
giving a map of keys to rules, and validating against them
*/
import Foundation
import URBNValidator
class Tester: Validateable {
typealias V = AnyObject
var requiredString: String?
var children = [String]()
func validationMap() -> [String : ValidatingValue<V>] {
return [
"requiredString": ValidatingValue(value: self.requiredString, rules: URBNRequiredRule()),
"children": ValidatingValue(value: self.children, rules: URBNMinLengthRule(minLength: 3))
]
}
@objc func valueForKey(key: String) -> AnyObject? {
let d: [String: AnyObject?] = [
"requiredString": self.requiredString,
"children": self.children
]
return d[key]!
}
}
let obj = Tester()
let validator = URBNValidator()
do {
try validator.validate(obj)
}
catch let err as NSError {
print(err.underlyingErrors!.map({ $0.localizedDescription }))
}
| mit |
googlearchive/science-journal-ios | ScienceJournalTests/WrappedModels/ExperimentLibraryTest.swift | 1 | 8488 | /*
* Copyright 2019 Google LLC. 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 XCTest
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
@testable import third_party_sciencejournal_ios_ScienceJournalProtos
class ExperimentLibraryTest: XCTestCase {
var experimentLibrary: ExperimentLibrary!
let clock = SettableClock(now: 1000)
override func setUp() {
super.setUp()
experimentLibrary = ExperimentLibrary(clock: clock)
}
func testExperimentArchived() {
experimentLibrary.setExperimentArchived(true, experimentID: "123")
XCTAssertNil(experimentLibrary.isExperimentArchived(withID: "123"))
experimentLibrary.addExperiment(withID: "123", fileID: "456")
XCTAssertFalse(experimentLibrary.isExperimentArchived(withID: "123")!)
experimentLibrary.setExperimentArchived(true, experimentID: "123")
XCTAssertTrue(experimentLibrary.isExperimentArchived(withID: "123")!)
experimentLibrary.setExperimentArchived(false, experimentID: "123")
XCTAssertFalse(experimentLibrary.isExperimentArchived(withID: "123")!)
}
func testExperimentDeleted() {
experimentLibrary.setExperimentDeleted(true, experimentID: "123")
XCTAssertNil(experimentLibrary.isExperimentDeleted(withID: "123"))
experimentLibrary.addExperiment(withID: "123", fileID: "456")
XCTAssertFalse(experimentLibrary.isExperimentDeleted(withID: "123")!)
experimentLibrary.setExperimentDeleted(true, experimentID: "123")
XCTAssertTrue(experimentLibrary.isExperimentDeleted(withID: "123")!)
experimentLibrary.setExperimentDeleted(false, experimentID: "123")
XCTAssertFalse(experimentLibrary.isExperimentDeleted(withID: "123")!)
}
func testExperimentLastOpened() {
experimentLibrary.setExperimentLastOpened(atTimestamp: 1098919555, experimentID: "123")
XCTAssertNil(experimentLibrary.experimentLastOpened(withID: "123"))
experimentLibrary.addExperiment(withID: "123", fileID: "456")
experimentLibrary.setExperimentLastOpened(atTimestamp: 1098919555, experimentID: "123")
XCTAssertEqual(1098919555, experimentLibrary.experimentLastOpened(withID: "123"))
experimentLibrary.setExperimentLastOpened(atTimestamp: 1526499485, experimentID: "123")
XCTAssertEqual(1526499485, experimentLibrary.experimentLastOpened(withID: "123"))
}
func testExperimentModified() {
experimentLibrary.setExperimentLastModified(atTimestamp: 1098919555, withExperimentID: "123")
XCTAssertNil(experimentLibrary.experimentLastModified(withID: "123"))
experimentLibrary.addExperiment(withID: "123", fileID: "456")
experimentLibrary.setExperimentLastModified(atTimestamp: 1098919555, withExperimentID: "123")
XCTAssertEqual(1098919555, experimentLibrary.experimentLastModified(withID: "123"))
experimentLibrary.setExperimentLastModified(atTimestamp: 1526499485, withExperimentID: "123")
XCTAssertEqual(1526499485, experimentLibrary.experimentLastModified(withID: "123"))
}
func testHasFileIDForExperiment() {
let experimentID = "789"
XCTAssertFalse(experimentLibrary.hasFileIDForExperiment(withID: experimentID),
"An experiment that has not been added should not have a file ID.")
experimentLibrary.addExperiment(withID: experimentID)
XCTAssertFalse(experimentLibrary.hasFileIDForExperiment(withID: experimentID),
"An experiment that has not set a file ID should not have a file ID.")
experimentLibrary.setFileID("100", forExperimentID: experimentID)
XCTAssertTrue(experimentLibrary.hasFileIDForExperiment(withID: experimentID),
"Once an experiment's file ID has been set, it should not a file ID.")
}
func testExperimentLibraryFromProto() {
let syncExperimentProto1 = GSJSyncExperiment()
syncExperimentProto1.experimentId = "apple"
let syncExperimentProto2 = GSJSyncExperiment()
syncExperimentProto2.experimentId = "banana"
let proto = GSJExperimentLibrary()
proto.folderId = "abc_id"
proto.syncExperimentArray = NSMutableArray(array: [syncExperimentProto1, syncExperimentProto2])
let experimentLibrary = ExperimentLibrary(proto: proto)
XCTAssertEqual("abc_id", experimentLibrary.folderID)
XCTAssertEqual(2, experimentLibrary.syncExperiments.count)
XCTAssertEqual("apple", experimentLibrary.syncExperiments[0].experimentID)
XCTAssertEqual("banana", experimentLibrary.syncExperiments[1].experimentID)
}
func testProtoFromExperimentLibrary() {
let clock = SettableClock(now: 1000)
let syncExperiment1 = SyncExperiment(experimentID: "cantaloupe", clock: clock)
let syncExperiment2 = SyncExperiment(experimentID: "date", clock: clock)
experimentLibrary.folderID = "def_id"
experimentLibrary.syncExperiments = [syncExperiment1, syncExperiment2]
let proto = experimentLibrary.proto
XCTAssertEqual("def_id", proto.folderId)
XCTAssertEqual(2, proto.syncExperimentArray_Count)
XCTAssertEqual(2, proto.syncExperimentArray.count)
let protoArray: [SyncExperiment] =
proto.syncExperimentArray.map { SyncExperiment(proto: $0 as! GSJSyncExperiment) }
XCTAssertEqual("cantaloupe", protoArray[0].experimentID)
XCTAssertEqual("date", protoArray[1].experimentID)
let proto2 = experimentLibrary.proto
XCTAssertEqual(proto, proto2)
XCTAssertFalse(proto === proto2)
}
func testDirtyState() {
XCTAssertTrue(experimentLibrary.isDirty, "Dirty state should default to true.")
experimentLibrary.isDirty = false
XCTAssertFalse(experimentLibrary.isDirty, "Dirty state should now be false.")
// Add a sync experiment first so it's there for the rest of the calls to use.
experimentLibrary.addExperiment(SyncExperiment(experimentID: "test_experiment_ID",
clock: Clock()))
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after adding a sync experiment.")
experimentLibrary.isDirty = false
experimentLibrary.setFileID("test_file_ID", forExperimentID: "test_experiment_ID")
XCTAssertTrue(experimentLibrary.isDirty, "Dirty state should be true after setting a file ID.")
experimentLibrary.isDirty = false
experimentLibrary.addExperiment(withID: "test_experiment_ID_2")
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after adding an experiment by ID.")
experimentLibrary.isDirty = false
experimentLibrary.setExperimentArchived(true, experimentID: "test_experiment_ID")
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after setting an experiment to archived.")
experimentLibrary.isDirty = false
experimentLibrary.setExperimentOpened(withExperimentID: "test_experiment_ID")
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after setting an experiment's last opened timestamp.")
experimentLibrary.isDirty = false
experimentLibrary.setExperimentModified(withExperimentID: "test_experiment_ID")
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after setting an experiment's last modified " +
"timestamp.")
// Test deleting last so the experiment is there for the rest of the calls to use.
experimentLibrary.isDirty = false
experimentLibrary.setExperimentDeleted(true, experimentID: "test_experiment_ID")
XCTAssertTrue(experimentLibrary.isDirty,
"Dirty state should be true after setting an experiment to deleted.")
}
func testAddExperimentLastModified() {
experimentLibrary.addExperiment(withID: "789", isArchived: true)
XCTAssertEqual(1000, experimentLibrary.experimentLastModified(withID: "789"))
experimentLibrary.addExperiment(withID: "567", lastModifiedTimestamp: 2100)
XCTAssertEqual(2100, experimentLibrary.experimentLastModified(withID: "567"))
}
}
| apache-2.0 |
mrchenhao/American-TV-Series-Calendar | American-tv-series-calendar/SettingTableViewController.swift | 1 | 6565 | //
// SettingTableViewController.swift
// American-tv-series-calendar
//
// Created by ChenHao on 10/27/15.
// Copyright © 2015 HarriesChen. All rights reserved.
//
import UIKit
import EventKitUI
class SettingTableViewController: UITableViewController {
var showStart: Bool = false
var showEnd: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "设置"
self.tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 2 && indexPath.section == 0 {
let dateCell: SettingDatePickerCell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! SettingDatePickerCell
dateCell.delegate = self
dateCell.dateType = .start
dateCell.datePickerView.date = NSDate.getDateByString(SettingManager.startTime)
dateCell.selectionStyle = .None
return dateCell
}
if indexPath.row == 4 && indexPath.section == 0 {
let dateCell: SettingDatePickerCell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! SettingDatePickerCell
dateCell.delegate = self
dateCell.dateType = .end
dateCell.datePickerView.date = NSDate.getDateByString(SettingManager.endTime)
dateCell.selectionStyle = .None
return dateCell
}
let cell = tableView.dequeueReusableCellWithIdentifier("settingBaseCell", forIndexPath: indexPath)
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
if indexPath.section == 0 {
if indexPath.row == 0 {
cell.textLabel?.text = "默认日历"
let userdefault: NSUserDefaults = NSUserDefaults.standardUserDefaults()
if (userdefault.valueForKey(Constant.defaultCalendar) != nil) {
let calendar:EKCalendar = EKManager.sharedInstance.getCalendarByIdentifer(userdefault.valueForKey(Constant.defaultCalendar) as! String)
cell.detailTextLabel?.text = calendar.title
} else {
cell.detailTextLabel?.text = EKManager.sharedInstance.getDefaultCalendar().title
}
}
if indexPath.row == 1 {
cell.textLabel?.text = "默认开始时间"
cell.detailTextLabel?.text = SettingManager.startTime
}
if indexPath.row == 3 {
cell.textLabel?.text = "默认结束时间"
cell.detailTextLabel?.text = SettingManager.endTime
}
if indexPath.row == 5 {
cell.textLabel?.text = "关于"
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
if indexPath.row == 0 {
let choose: EKCalendarChooser = EKCalendarChooser(selectionStyle: .Single, displayStyle: .WritableCalendarsOnly, entityType: .Event, eventStore: EKManager.sharedInstance.store)
choose.showsDoneButton = true
choose.delegate = self
self.navigationController?.pushViewController(choose, animated: true)
}
if indexPath.row == 1 {
showStart = !showStart
showEnd = false
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic)
}
if indexPath.row == 3 {
showEnd = !showEnd
showStart = false
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic)
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 2 {
if showStart {
return 216
}
return 0
}
if indexPath.row == 4 {
if showEnd {
return 216
}
return 0
}
return 44
}
}
extension SettingTableViewController: SettingDatePickerCellDelegate {
func datePicker(datePicker: datePickerType, didChangeDate date: NSDate) {
switch datePicker {
case .start:
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))!
cell.detailTextLabel?.text = date.getHourAndMin()
SettingManager.startTime = date.getHourAndMin()
case .end:
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))!
cell.detailTextLabel?.text = date.getHourAndMin()
SettingManager.endTime = date.getHourAndMin()
}
}
}
extension SettingTableViewController: EKCalendarChooserDelegate {
func calendarChooserDidFinish(calendarChooser: EKCalendarChooser) {
if calendarChooser.selectedCalendars.count > 0 {
let userdefault: NSUserDefaults = NSUserDefaults.standardUserDefaults()
userdefault.setValue(calendarChooser.selectedCalendars.first!.calendarIdentifier, forKey: Constant.defaultCalendar)
userdefault.synchronize()
let cell: UITableViewCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))!
cell.detailTextLabel!.text = calendarChooser.selectedCalendars.first!.title
calendarChooser.navigationController?.popViewControllerAnimated(true)
}
}
}
extension NSDate {
func getHourAndMin() -> String {
let calendar = NSCalendar.currentCalendar()
let components:NSDateComponents = calendar.components([.Hour, .Minute], fromDate: self)
return String(format: "%.2d:%.2d", arguments: [components.hour,components.minute])
}
}
| mit |
mleiv/IBStyler | Initial Code Files/IBStyles/IBStylable.swift | 2 | 812 | //
// IBStylable.swift
//
// Created by Emily Ivie on 3/4/15.
//
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import UIKit
/// Protocol for stylable UIKit elements.
/// See IBStyledThings for examples.
public protocol IBStylable where Self: UIView { // Swift 4.2 do not remove class
var styler: IBStyler? { get }
var identifier: String? { get }
var defaultIdentifier: String { get } // optional
func applyStyles() // optional
func changeContentSizeCategory() // optional
}
extension IBStylable {
public var defaultIdentifier: String { return "" }
public func applyStyles() {}
public func changeContentSizeCategory() {}
}
| mit |
rringham/ios-motion-machinelearning | src/MotionMachineLearning/MotionMachineLearning/AppDelegate.swift | 1 | 2151 | //
// AppDelegate.swift
// MotionMachineLearning
//
// Created by Rob Ringham on 1/4/16.
// Copyright © 2016 Ringham. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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 throttle down OpenGL ES frame rates. 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 inactive 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 |
mro/ShaarliOS | swift4/ShaarliOS/3rd/Disposable.swift | 1 | 1516 | // https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Disposable.swift
// Disposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/*
import Foundation
/// Represents a disposable resource.
public protocol Disposable {
/// Dispose resource.
func dispose()
}
// https://www.objc.io/blog/2018/04/24/bindings-with-kvo-and-keypaths/
// successor of https://github.com/objcio/issue-7-lab-color-space-explorer/blob/master/Lab%20Color%20Space%20Explorer/KeyValueObserver.m
extension NSObjectProtocol where Self: NSObject {
func observe<Value>(_ keyPath: KeyPath<Self, Value>,
onChange: @escaping (Value) -> ()) -> Disposable
{
let observation = observe(keyPath, options: [.initial, .new]) { _, change in
// The guard is because of https://bugs.swift.org/browse/SR-6066
guard let newValue = change.newValue else { return }
onChange(newValue)
}
return Disposable { observation.invalidate() }
}
}
// https://www.objc.io/blog/2018/04/24/bindings-with-kvo-and-keypaths/
extension NSObjectProtocol where Self: NSObject {
func bind<Value, Target>(_ sourceKeyPath: KeyPath<Self, Value>,
to target: Target,
at targetKeyPath: ReferenceWritableKeyPath<Target, Value>) -> Disposable
{
return observe(sourceKeyPath) { target[keyPath: targetKeyPath] = $0 }
}
}
*/
| gpl-3.0 |
airspeedswift/swift | test/SourceKit/CodeComplete/complete_checkdeps_avoid_check.swift | 4 | 2606 | import ClangFW
import SwiftFW
func foo() {
/*HERE*/
}
// Checks that, due to default check delay, a modification will be ignored and fast completion will still activate.
// REQUIRES: shell
// RUN: %empty-directory(%t/Frameworks)
// RUN: %empty-directory(%t/MyProject)
// RUN: COMPILER_ARGS=( \
// RUN: -target %target-triple \
// RUN: -module-name MyProject \
// RUN: -F %t/Frameworks \
// RUN: -I %t/MyProject \
// RUN: -import-objc-header %t/MyProject/Bridging.h \
// RUN: %t/MyProject/Library.swift \
// RUN: %s \
// RUN: )
// RUN: INPUT_DIR=%S/Inputs/checkdeps
// RUN: DEPCHECK_INTERVAL=1
// RUN: SLEEP_TIME=2
// RUN: cp -R $INPUT_DIR/MyProject %t/
// RUN: cp -R $INPUT_DIR/ClangFW.framework %t/Frameworks/
// RUN: %empty-directory(%t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule)
// RUN: %target-swift-frontend -emit-module -module-name SwiftFW -o %t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule/%target-swiftmodule-name $INPUT_DIR/SwiftFW_src/Funcs.swift
// RUN: %sourcekitd-test \
// RUN: -req=global-config == \
// RUN: -shell -- echo "### Initial" == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \
// RUN: -shell -- echo '### Modify framework (c)' == \
// RUN: -shell -- sleep $SLEEP_TIME == \
// RUN: -shell -- cp -R $INPUT_DIR/ClangFW.framework_mod/* %t/Frameworks/ClangFW.framework/ == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \
// RUN: -req=global-config -completion-check-dependency-interval ${DEPCHECK_INTERVAL} == \
// RUN: -shell -- echo '### Checking dependencies' == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} \
// RUN: | %FileCheck %s
// CHECK-LABEL: ### Initial
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK-NOT: key.reusingastcontext: 1
// CHECK-LABEL: ### Modify framework (c)
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK: key.reusingastcontext: 1
// CHECK-LABEL: ### Checking dependencies
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc_mod()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK-NOT: key.reusingastcontext: 1
| apache-2.0 |
JuanjoArreola/AllCache | Sources/ImageCache/ImageResizer.swift | 1 | 3133 | //
// ImageResizer.swift
// ImageCache
//
// Created by JuanJo on 31/08/20.
//
import Foundation
import AllCache
#if os(OSX)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
public enum ImageProcessError: Error {
case resizeError
}
private let resizeFunctions: [DefaultImageResizer.ContentMode: (CGSize, CGSize) -> CGRect] = [
.scaleAspectFit: aspectFit,
.scaleAspectFill: aspectFill,
.center: center,
.top: top,
.bottom: bottom,
.left: left,
.right: right,
.topLeft: topLeft,
.topRight: topRight,
.bottomLeft: bottomLeft,
.bottomRight: bottomRight,
]
public final class DefaultImageResizer: Processor<Image> {
public enum ContentMode: Int {
case scaleToFill, scaleAspectFit, scaleAspectFill
case redraw
case center, top, bottom, left, right
case topLeft, topRight, bottomLeft, bottomRight
}
public var size: CGSize
public var scale: CGFloat
public var mode: ContentMode
public init(size: CGSize, scale: CGFloat, mode: ContentMode) {
self.size = size
self.scale = scale
self.mode = mode
super.init(identifier: "\(size.width)x\(size.height),\(scale),\(mode.rawValue)")
}
public override func process(_ instance: Image) throws -> Image {
var image = instance
if shouldScale(image: image) {
guard let scaledImage = self.scale(image: instance) else {
throw ImageProcessError.resizeError
}
image = scaledImage
}
if let nextProcessor = next {
return try nextProcessor.process(image)
}
return image
}
func shouldScale(image: Image) -> Bool {
#if os(OSX)
return image.size != size
#elseif os(iOS) || os(tvOS) || os(watchOS)
let scale = self.scale != 0.0 ? self.scale : UIScreen.main.scale
return image.size != size || image.scale != scale
#endif
}
#if os(iOS) || os(tvOS) || os(watchOS)
public func scale(image: Image) -> Image? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
image.draw(in: drawRect(for: image))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
#else
public func scale(image: Image) -> Image? {
let scaledImage = Image(size: size)
scaledImage.lockFocus()
guard let context = NSGraphicsContext.current else {
return nil
}
context.imageInterpolation = .high
image.draw(in: drawRect(for: image), from: NSRect(origin: .zero, size: image.size), operation: .copy, fraction: 1)
scaledImage.unlockFocus()
return scaledImage
}
#endif
public func drawRect(for image: Image) -> CGRect {
if let method = resizeFunctions[mode] {
return method(size, image.size)
}
return CGRect(origin: CGPoint.zero, size: size)
}
}
| mit |
tache/SwifterSwift | Tests/SwiftStdlibTests/StringExtensionsTests.swift | 1 | 18711 | //
// StringExtensionsTests.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/27/16.
// Copyright © 2016 SwifterSwift
//
import XCTest
@testable import SwifterSwift
final class StringExtensionsTests: XCTestCase {
override func setUp() {
super.setUp()
NSTimeZone.default = NSTimeZone.system
}
func testBase64Decoded() {
XCTAssertEqual("SGVsbG8gV29ybGQh".base64Decoded, "Hello World!")
XCTAssertNil("hello".base64Decoded)
}
func testBase64Encoded() {
XCTAssertEqual("Hello World!".base64Encoded, "SGVsbG8gV29ybGQh")
}
func testCharactersArray() {
let str = "Swift"
let chars = [Character("S"), Character("w"), Character("i"), Character("f"), Character("t")]
XCTAssertEqual(str.charactersArray, chars)
}
func testCamelCased() {
XCTAssertEqual("Hello test".camelCased, "helloTest")
XCTAssertEqual("Hellotest".camelCased, "hellotest")
}
func testCamelize() {
var str = "Hello test"
str.camelize()
XCTAssertEqual(str, "helloTest")
}
func testContain() {
XCTAssert("Hello Tests".contains("Hello", caseSensitive: true))
XCTAssert("Hello Tests".contains("hello", caseSensitive: false))
}
func testContainEmoji() {
XCTAssert("Hello 😂".containEmoji)
XCTAssertFalse("Hello ;)".containEmoji)
}
func testCount() {
XCTAssertEqual("Hello This Tests".count(of: "T"), 2)
XCTAssertEqual("Hello This Tests".count(of: "t"), 1)
XCTAssertEqual("Hello This Tests".count(of: "T", caseSensitive: false), 3)
XCTAssertEqual("Hello This Tests".count(of: "t", caseSensitive: false), 3)
}
func testEnd() {
XCTAssert("Hello Test".ends(with: "test", caseSensitive: false))
XCTAssert("Hello Tests".ends(with: "sts"))
}
func testFirstCharacter() {
XCTAssertNil("".firstCharacterAsString)
XCTAssertNotNil("Hello".firstCharacterAsString)
XCTAssertEqual("Hello".firstCharacterAsString, "H")
}
func testHasLetters() {
XCTAssert("hsj 1 wq3".hasLetters)
XCTAssertFalse("123".hasLetters)
XCTAssert("Hello test".hasLetters)
}
func testHasNumbers() {
XCTAssert("hsj 1 wq3".hasNumbers)
XCTAssert("123".hasNumbers)
XCTAssertFalse("Hello test".hasNumbers)
}
func testIsAlphabetic() {
XCTAssert("abc".isAlphabetic)
XCTAssertFalse("123abc".isAlphabetic)
XCTAssertFalse("123".isAlphabetic)
}
func testIsAlphaNumeric() {
XCTAssert("123abc".isAlphaNumeric)
XCTAssertFalse("123".isAlphaNumeric)
XCTAssertFalse("abc".isAlphaNumeric)
}
func testIsEmail() {
XCTAssert("omaralbeik@gmail.com".isEmail)
XCTAssertFalse("omaralbeik@gmailcom".isEmail)
XCTAssertFalse("omaralbeikgmail.com".isEmail)
}
func testIsValidUrl() {
XCTAssert("https://google.com".isValidUrl)
XCTAssert("http://google.com".isValidUrl)
XCTAssert("ftp://google.com".isValidUrl)
}
func testIsValidSchemedUrl() {
XCTAssertFalse("Hello world!".isValidSchemedUrl)
XCTAssert("https://google.com".isValidSchemedUrl)
XCTAssert("ftp://google.com".isValidSchemedUrl)
XCTAssertFalse("google.com".isValidSchemedUrl)
}
func testIsValidHttpsUrl() {
XCTAssertFalse("Hello world!".isValidHttpsUrl)
XCTAssert("https://google.com".isValidHttpsUrl)
XCTAssertFalse("http://google.com".isValidHttpsUrl)
XCTAssertFalse("google.com".isValidHttpsUrl)
}
func testIsValidHttpUrl() {
XCTAssertFalse("Hello world!".isValidHttpUrl)
XCTAssert("http://google.com".isValidHttpUrl)
XCTAssertFalse("google.com".isValidHttpUrl)
}
func testIsValidFileURL() {
XCTAssertFalse("Hello world!".isValidFileUrl)
XCTAssert("file://var/folder/file.txt".isValidFileUrl)
XCTAssertFalse("google.com".isValidFileUrl)
}
func testIsNumeric() {
XCTAssert("123".isNumeric)
XCTAssertFalse("123abc".isNumeric)
XCTAssertFalse("abc".isNumeric)
}
func testHasUniqueCharacters() {
XCTAssert("swift".hasUniqueCharacters())
XCTAssertFalse("language".hasUniqueCharacters())
XCTAssertFalse("".hasUniqueCharacters())
}
func testLastCharacter() {
XCTAssertNotNil("Hello".lastCharacterAsString)
XCTAssertEqual("Hello".lastCharacterAsString, "o")
XCTAssertNil("".lastCharacterAsString)
}
func testLatinize() {
var str = "Hëllô Teśt"
str.latinize()
XCTAssertEqual(str, "Hello Test")
}
func testLatinized() {
XCTAssertEqual("Hëllô Teśt".latinized, "Hello Test")
}
func testLines() {
XCTAssertEqual("Hello\ntest".lines(), ["Hello", "test"])
}
func testMostCommonCharacter() {
let mostCommonCharacter = "This is a test, since e is appearing every where e should be the common character".mostCommonCharacter
XCTAssertEqual(mostCommonCharacter(), "e")
XCTAssertNil("".mostCommonCharacter())
}
func testRandom() {
let str1 = String.random(ofLength: 10)
XCTAssertEqual(str1.count, 10)
let str2 = String.random(ofLength: 10)
XCTAssertEqual(str2.count, 10)
XCTAssertNotEqual(str1, str2)
XCTAssertEqual(String.random(ofLength: 0), "")
}
func testReverse() {
var str = "Hello"
str.reverse()
XCTAssertEqual(str, "olleH")
}
func testSlice() {
XCTAssertEqual("12345678".slicing(from: 2, length: 3), "345")
XCTAssertEqual("12345678".slicing(from: 2, length: 0), "")
XCTAssertNil("12345678".slicing(from: 12, length: 0))
XCTAssertEqual("12345678".slicing(from: 2, length: 100), "345678")
var str = "12345678"
str.slice(from: 2, length: 3)
XCTAssertEqual(str, "345")
str = "12345678"
str.slice(from: 2, length: 0)
print(str)
XCTAssertEqual(str, "")
str = "12345678"
str.slice(from: 12, length: 0)
XCTAssertEqual(str, "12345678")
str = "12345678"
str.slice(from: 2, length: 100)
XCTAssertEqual(str, "345678")
str = "12345678"
str.slice(from: 2, to: 5)
XCTAssertEqual(str, "345")
str = "12345678"
str.slice(from: 2, to: 1)
XCTAssertEqual(str, "12345678")
str = "12345678"
str.slice(at: 2)
XCTAssertEqual(str, "345678")
}
func testStart() {
XCTAssert("Hello Test".starts(with: "hello", caseSensitive: false))
XCTAssert("Hello Tests".starts(with: "He"))
}
func testDateWithFormat() {
let dateString = "2012-12-08 17:00:00.0"
let date = dateString.date(withFormat: "yyyy-dd-MM HH:mm:ss.S")
XCTAssertNotNil(date)
XCTAssertNil(dateString.date(withFormat: "Hello world!"))
}
func testOperators() {
let sa = "sa"
XCTAssertEqual(sa * 5, "sasasasasa")
XCTAssertEqual(5 * sa, "sasasasasa")
XCTAssertEqual(sa * 0, "")
XCTAssertEqual(0 * sa, "")
XCTAssertEqual(sa * -5, "")
XCTAssertEqual(-5 * sa, "")
}
func testToBool() {
XCTAssertNotNil("1".bool)
XCTAssert("1".bool!)
XCTAssertNotNil("false".bool)
XCTAssertFalse("false".bool!)
XCTAssertNil("8s".bool)
}
func testDate() {
let dateFromStr = "2015-06-01".date
XCTAssertNotNil(dateFromStr)
XCTAssertEqual(dateFromStr?.year, 2015)
XCTAssertEqual(dateFromStr?.month, 6)
XCTAssertEqual(dateFromStr?.day, 1)
}
func testDateTime() {
let dateFromStr = "2015-06-01 14:23:09".dateTime
XCTAssertNotNil(dateFromStr)
XCTAssertEqual(dateFromStr?.year, 2015)
XCTAssertEqual(dateFromStr?.month, 6)
XCTAssertEqual(dateFromStr?.day, 1)
XCTAssertEqual(dateFromStr?.hour, 14)
XCTAssertEqual(dateFromStr?.minute, 23)
XCTAssertEqual(dateFromStr?.second, 9)
}
func testDouble() {
XCTAssertNotNil("8".double())
XCTAssertEqual("8".double(), 8)
XCTAssertNotNil("8.23".double(locale: Locale(identifier: "en_US_POSIX")))
XCTAssertEqual("8.23".double(locale: Locale(identifier: "en_US_POSIX")), 8.23)
XCTAssertNil("8s".double())
}
func testFloat() {
XCTAssertNotNil("8".float())
XCTAssertEqual("8".float(), 8)
XCTAssertNotNil("8.23".float(locale: Locale(identifier: "en_US_POSIX")))
XCTAssertEqual("8.23".float(locale: Locale(identifier: "en_US_POSIX")), Float(8.23))
XCTAssertNil("8s".float())
}
func testCgFloat() {
XCTAssertNotNil("8".cgFloat())
XCTAssertEqual("8".cgFloat(), 8)
XCTAssertNotNil("8.23".cgFloat(locale: Locale(identifier: "en_US_POSIX")))
XCTAssertEqual("8.23".cgFloat(locale: Locale(identifier: "en_US_POSIX")), CGFloat(8.23))
XCTAssertNil("8s".cgFloat())
}
func testInt() {
XCTAssertNotNil("8".int)
XCTAssertEqual("8".int, 8)
XCTAssertNil("8s".int)
}
func testLoremIpsum() {
// https://www.lipsum.com/
let completeLoremIpsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
XCTAssertEqual(String.loremIpsum(), completeLoremIpsum)
XCTAssertEqual(String.loremIpsum(ofLength: 0), "")
XCTAssertEqual(String.loremIpsum(ofLength: 26), "Lorem ipsum dolor sit amet")
}
func testUrl() {
XCTAssertNil("hello world".url)
let google = "https://www.google.com"
XCTAssertEqual(google.url, URL(string: google))
}
func testTrim() {
var str = "\n Hello \n "
str.trim()
XCTAssertEqual(str, "Hello")
}
func testTrimmed() {
XCTAssertEqual("\n Hello \n ".trimmed, "Hello")
}
func testTruncate() {
var str = "This is a very long sentence"
str.truncate(toLength: 14)
XCTAssertEqual(str, "This is a very...")
str = "This is a very long sentence"
str.truncate(toLength: 14, trailing: nil)
XCTAssertEqual(str, "This is a very")
str = "This is a short sentence"
str.truncate(toLength: 100)
XCTAssertEqual(str, "This is a short sentence")
str.truncate(toLength: -1)
XCTAssertEqual(str, "This is a short sentence")
}
func testTruncated() {
XCTAssertEqual("This is a very long sentence".truncated(toLength: 14), "This is a very...")
XCTAssertEqual("This is a very long sentence".truncated(toLength: 14, trailing: nil), "This is a very")
XCTAssertEqual("This is a short sentence".truncated(toLength: 100), "This is a short sentence")
}
func testUnicodeArray() {
XCTAssertEqual("Hello".unicodeArray(), [72, 101, 108, 108, 111])
}
func testUrlDecode() {
var url = "it's%20easy%20to%20encode%20strings"
url.urlDecode()
XCTAssertEqual(url, "it's easy to encode strings")
}
func testUrlDecoded() {
XCTAssertEqual("it's%20easy%20to%20encode%20strings".urlDecoded, "it's easy to encode strings")
XCTAssertEqual("%%".urlDecoded, "%%")
}
func testUrlEncode() {
var url = "it's easy to encode strings"
url.urlEncode()
XCTAssertEqual(url, "it's%20easy%20to%20encode%20strings")
}
func testUrlEncoded() {
XCTAssertEqual("it's easy to encode strings".urlEncoded, "it's%20easy%20to%20encode%20strings")
}
func testMatches() {
XCTAssertTrue("123".matches(pattern: "\\d{3}"))
XCTAssertFalse("dasda".matches(pattern: "\\d{3}"))
XCTAssertFalse("notanemail.com".matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"))
XCTAssertTrue("email@mail.com".matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"))
}
func testWithoutSpacesAndNewLines() {
XCTAssertEqual("Hello \n Test".withoutSpacesAndNewLines, "HelloTest")
}
func testSubscript() {
let str = "Hello world!"
XCTAssertEqual(str[safe: 1], "e")
XCTAssertNil(str[safe: 18])
XCTAssertEqual(str[safe: 1..<5], "ello")
XCTAssertNil(str[safe: 10..<18])
XCTAssertNil(""[safe: 1..<2])
XCTAssertEqual(str[safe: 0...4], "Hello")
XCTAssertNil(str[safe: 10...18])
XCTAssertNil(""[safe: 1...2])
}
func testCopyToPasteboard() {
let str = "Hello world!"
#if os(iOS)
str.copyToPasteboard()
let strFromPasteboard = UIPasteboard.general.string
XCTAssertEqual(strFromPasteboard, str)
#elseif os(macOS)
str.copyToPasteboard()
let strFromPasteboard = NSPasteboard.general.string(forType: .string)
XCTAssertEqual(strFromPasteboard, str)
#endif
}
func testInitRandomOfLength() {
let str1 = String(randomOfLength: 10)
XCTAssertEqual(str1.count, 10)
let str2 = String(randomOfLength: 10)
XCTAssertEqual(str2.count, 10)
XCTAssertNotEqual(str1, str2)
XCTAssertEqual(String(randomOfLength: 0), "")
}
func testInitFromBase64() {
XCTAssertNotNil(String(base64: "SGVsbG8gV29ybGQh"))
XCTAssertEqual(String(base64: "SGVsbG8gV29ybGQh"), "Hello World!")
XCTAssertNil(String(base64: "hello"))
}
func testNSString() {
XCTAssertEqual("Hello".nsString, NSString(string: "Hello"))
}
func testLastPathComponent() {
let string = "hello"
let nsString = NSString(string: "hello")
XCTAssertEqual(string.lastPathComponent, nsString.lastPathComponent)
}
func testLastPathExtension() {
let string = "hello"
let nsString = NSString(string: "hello")
XCTAssertEqual(string.pathExtension, nsString.pathExtension)
}
func testLastDeletingLastPathComponent() {
let string = "hello"
let nsString = NSString(string: "hello")
XCTAssertEqual(string.deletingLastPathComponent, nsString.deletingLastPathComponent)
}
func testLastDeletingPathExtension() {
let string = "hello"
let nsString = NSString(string: "hello")
XCTAssertEqual(string.deletingPathExtension, nsString.deletingPathExtension)
}
func testLastPathComponents() {
let string = "hello"
let nsString = NSString(string: "hello")
XCTAssertEqual(string.pathComponents, nsString.pathComponents)
}
func testAppendingPathComponent() {
let string = "hello".appendingPathComponent("world")
let nsString = NSString(string: "hello").appendingPathComponent("world")
XCTAssertEqual(string, nsString)
}
func testAppendingPathExtension() {
let string = "hello".appendingPathExtension("world")
let nsString = NSString(string: "hello").appendingPathExtension("world")
XCTAssertEqual(string, nsString)
}
#if !os(tvOS) && !os(watchOS)
func testBold() {
let boldString = "hello".bold
let attrs = boldString.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, boldString.length))
XCTAssertNotNil(attrs[NSAttributedStringKey.font])
#if os(macOS)
guard let font = attrs[.font] as? NSFont else {
XCTFail()
return
}
XCTAssertEqual(font, NSFont.boldSystemFont(ofSize: NSFont.systemFontSize))
#elseif os(iOS)
guard let font = attrs[NSAttributedStringKey.font] as? UIFont else {
XCTFail()
return
}
XCTAssertEqual(font, UIFont.boldSystemFont(ofSize: UIFont.systemFontSize))
#endif
}
#endif
func testUnderline() {
let underlinedString = "hello".underline
let attrs = underlinedString.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, underlinedString.length))
XCTAssertNotNil(attrs[NSAttributedStringKey.underlineStyle])
guard let style = attrs[NSAttributedStringKey.underlineStyle] as? Int else {
XCTFail()
return
}
XCTAssertEqual(style, NSUnderlineStyle.styleSingle.rawValue)
}
func testStrikethrough() {
let strikedthroughString = "hello".strikethrough
let attrs = strikedthroughString.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, strikedthroughString.length))
XCTAssertNotNil(attrs[NSAttributedStringKey.strikethroughStyle])
guard let style = attrs[NSAttributedStringKey.strikethroughStyle] as? NSNumber else {
XCTFail()
return
}
XCTAssertEqual(style, NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int))
}
#if os(iOS)
func testItalic() {
let italicString = "hello".italic
let attrs = italicString.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, italicString.length))
XCTAssertNotNil(attrs[NSAttributedStringKey.font])
guard let font = attrs[NSAttributedStringKey.font] as? UIFont else {
XCTFail()
return
}
XCTAssertEqual(font, UIFont.italicSystemFont(ofSize: UIFont.systemFontSize))
}
#endif
func testColored() {
let coloredString = "hello".colored(with: .orange)
let attrs = coloredString.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, coloredString.length))
XCTAssertNotNil(attrs[NSAttributedStringKey.foregroundColor])
#if os(macOS)
guard let color = attrs[.foregroundColor] as? NSColor else {
XCTFail()
return
}
XCTAssertEqual(color, NSColor.orange)
#else
guard let color = attrs[NSAttributedStringKey.foregroundColor] as? UIColor else {
XCTFail()
return
}
XCTAssertEqual(color, UIColor.orange)
#endif
}
func testWords() {
XCTAssertEqual("Swift is amazing".words(), ["Swift", "is", "amazing"])
}
func testWordsCount() {
XCTAssertEqual("Swift is amazing".wordCount(), 3)
}
func testPaddingStart() {
XCTAssertEqual("str".paddingStart(10), " str")
XCTAssertEqual("str".paddingStart(10, with: "br"), "brbrbrbstr")
XCTAssertEqual("str".paddingStart(5, with: "brazil"), "brstr")
XCTAssertEqual("str".paddingStart(6, with: "a"), "aaastr")
XCTAssertEqual("str".paddingStart(6, with: "abc"), "abcstr")
XCTAssertEqual("str".paddingStart(2), "str")
}
func testPaddingEnd() {
XCTAssertEqual("str".paddingEnd(10), "str ")
XCTAssertEqual("str".paddingEnd(10, with: "br"), "strbrbrbrb")
XCTAssertEqual("str".paddingEnd(5, with: "brazil"), "strbr")
XCTAssertEqual("str".paddingEnd(6, with: "a"), "straaa")
XCTAssertEqual("str".paddingEnd(6, with: "abc"), "strabc")
XCTAssertEqual("str".paddingEnd(2), "str")
}
func testPadStart() {
var str: String = "str"
str.padStart(10)
XCTAssertEqual(str, " str")
str = "str"
str.padStart(10, with: "br")
XCTAssertEqual(str, "brbrbrbstr")
str = "str"
str.padStart(5, with: "brazil")
XCTAssertEqual(str, "brstr")
str = "str"
str.padStart(6, with: "a")
XCTAssertEqual(str, "aaastr")
str = "str"
str.padStart(6, with: "abc")
XCTAssertEqual(str, "abcstr")
str = "str"
str.padStart(2)
XCTAssertEqual(str, "str")
}
func testPadEnd() {
var str: String = "str"
str.padEnd(10)
XCTAssertEqual(str, "str ")
str = "str"
str.padEnd(10, with: "br")
XCTAssertEqual(str, "strbrbrbrb")
str = "str"
str.padEnd(5, with: "brazil")
XCTAssertEqual(str, "strbr")
str = "str"
str.padEnd(6, with: "a")
XCTAssertEqual(str, "straaa")
str = "str"
str.padEnd(6, with: "abc")
XCTAssertEqual(str, "strabc")
str = "str"
str.padEnd(2)
XCTAssertEqual(str, "str")
}
}
| mit |
ykws/yomblr | yomblr/CroppedViewController.swift | 1 | 1425 | //
// CroppedViewController.swift
// yomblr
//
// Created by Yoshiyuki Kawashima on 2017/06/22.
// Copyright © 2017 ykws. All rights reserved.
//
import UIKit
import TMTumblrSDK
import MBProgressHUD
import Firebase
class CroppedViewController: UIViewController {
// MARK: - Properties
var blogName: String!
var image: UIImage!
var postUrl: String!
// MARK: - Outlets
@IBOutlet weak var croppedView: UIImageView!
// MARK: - Actions
@IBAction func post(_ sender: Any) {
logEvent(title: "Post", type: "Button")
guard let base64EncodedString = UIImagePNGRepresentation(image)?.base64EncodedString() else {
showMessage("Can't Base64 encode.")
return
}
requestPhotoPost(withImageBase64EncodedString: base64EncodedString)
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setApplicationColor()
croppedView.image = image
}
// MARK: - Tumblr
func requestPhotoPost(withImageBase64EncodedString data64: String) {
TMAPIClient.sharedInstance().post(blogName, type: "photo", parameters: ["link": postUrl, "data64": data64], callback: { response, error in
if (error != nil) {
self.showError(error!)
}
})
navigationController?.popToViewController(navigationController!.viewControllers[(navigationController?.viewControllers.count)! - 3], animated: true)
}
}
| mit |
trujillo138/MyExpenses | MyExpenses/MyExpenses/Services/ModelController.swift | 1 | 1168 | //
// ModelController.swift
// MyExpenses
//
// Created by Tomas Trujillo on 5/22/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import Foundation
class ModelController {
//MARK: Properties
var user: User
private let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private var expensesURL: URL {
return documentsDirectoryURL.appendingPathComponent("Expenses").appendingPathExtension("plist")
}
//MARK: Model methods
func save(_ user: User) {
self.user = user
saveData()
}
//MARK: Loading and Saving
required init() {
user = User()
loadData()
}
private func loadData() {
guard let expenseModelPlist = NSDictionary.init(contentsOf: expensesURL) as? [String: AnyObject] else {
return
}
user = User(plist: expenseModelPlist)
}
private func saveData() {
let expenseDictionary = user.plistRepresentation as NSDictionary
expenseDictionary.write(to: expensesURL, atomically: true)
}
}
| apache-2.0 |
tbaranes/SwiftyUtils | Sources/Protocols/Swift/Occupiable.swift | 1 | 733 | //
// Created by Tom Baranes on 24/04/16.
// Copyright © 2016 Tom Baranes. All rights reserved.
//
import Foundation
public protocol Occupiable {
var isEmpty: Bool { get }
var isNotEmpty: Bool { get }
}
extension Occupiable {
public var isNotEmpty: Bool {
!isEmpty
}
}
extension String: Occupiable { }
extension Array: Occupiable { }
extension Dictionary: Occupiable { }
extension Set: Occupiable { }
extension Optional where Wrapped: Occupiable {
public var isNilOrEmpty: Bool {
switch self {
case .none:
return true
case .some(let value):
return value.isEmpty
}
}
public var isNotNilNotEmpty: Bool {
!isNilOrEmpty
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11776-swift-sourcemanager-getmessage.swift | 11 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a(
= {
var b = {
class A {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14435-swift-sourcemanager-getmessage.swift | 11 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let h = == {
} ( [ {
case
let {
init( ) {
class
case ,
| mit |
aofan/ZKSwift | ZKSwift/ZKBaseTableViewController.swift | 1 | 5707 | //
// ZKBaseTableViewController.swift
// ZKSwift
//
// Created by lizhikai on 16/7/4.
// Copyright © 2016年 ZK. All rights reserved.
//
import UIKit
public class ZKBaseTableViewController: UITableViewController {
/// 数据源
public var dataArray : Array<AnyObject>?;
/// 是否分组
public var isGroup:Bool = false;
/// 默认每页10条数据
public var pageSize = 10;
/// 开始页 默认第一页开始的
public var startPageNum = 1;
/// 当前页页码
public var pageNum = 1;
/// 是否第一次进行网络请求
public var isFirstRequest = true;
/// 是否有数据
public var isHaveData : Bool!{
get{
if self.dataArray?.count > 0 {
return true;
}
return false;
}
}
/**
请求数据 要求子类实现
*/
public func loadListRequest(){}
/**
请求更多数据 要求子类实现
*/
public func loadMoreListRequest(){}
/**
全部加载完成
*/
public func loadAllFinish(){}
/**
请求成功
*/
public func loadRequestSuccess(){}
/**
请求失败
*/
public func loadRequestFail(){}
override public func viewDidLoad() {
super.viewDidLoad()
self.pageNum = self.startPageNum;
}
// MARK: - tableView数据展示的处理
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//分组
if isGroup {
//有数据
if (self.dataArray != nil) {
return (self.dataArray?.count)!;
}
//无数据
return 0;
}
//不分组
return 1;
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//分组
if isGroup {
//有数据
if (self.dataArray != nil) {
return self.dataArray![section].count
}
//没数据
return 0;
}else{//不分组
//没数据
if ((self.dataArray?.count) == nil) {
return 0;
}
//有数据
return (self.dataArray?.count)!;
}
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let baseModel : ZKBaseModel? = self.indexPathForSource(indexPath);
return self.indexPathWithSourceForCell(indexPath, baseModel: baseModel);
}
/**
根据数据模型和索引创建对应的cell
- parameter indexPath: 索引
- parameter baseModel: 数据模型
- returns: cell
*/
private func indexPathWithSourceForCell( indexPath : NSIndexPath, baseModel : ZKBaseModel?) -> ZKBaseTableViewCell{
var cell : ZKBaseTableViewCell?;
let reuseIdentifier = String(baseModel!.cellClass!);
//是否加载xib 处理展示的cell
if baseModel?.isloadNib == true {
let nib = UINib.init( nibName: reuseIdentifier, bundle:NSBundle.mainBundle());
tableView.registerNib( nib, forCellReuseIdentifier: reuseIdentifier );
cell = tableView.dequeueReusableCellWithIdentifier( reuseIdentifier, forIndexPath: indexPath ) as? ZKBaseTableViewCell;
}else{
let type = baseModel!.cellClass as! ZKBaseTableViewCell.Type;
//对于Cell复用的处理
cell = tableView.dequeueReusableCellWithIdentifier( reuseIdentifier ) as? ZKBaseTableViewCell;
if cell == nil {
cell = type.init( style:UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier );
}
}
cell!.source = baseModel;
cell!.indexPath = indexPath;
cell?.cellEventHandler = cellEventHandler;
return cell!;
}
// MARK: - cell的点击事件处理
override public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.didSelectCell(self.indexPathForSource(indexPath));
}
/**
cell 的整体点击事件 子类要想响应点击事件必须掉用此方法
- parameter source: 数据模型
*/
public func didSelectCell( source : ZKBaseModel ) {
self.cellEventHandler(source);
}
/**
cell 的事件处理 子类用到时候需要重写
- parameter source: 数据模型
- parameter cell: 发生事件的cell
- parameter target: 区分同一个cell上的不同事件的标志
- parameter indexPath: 索引
*/
public func cellEventHandler( source : ZKBaseModel, cell : ZKBaseTableViewCell? = nil, target : AnyObject? = nil, indexPath : NSIndexPath? = nil ){
}
// MARK: - 根据cell获取数据模型
/**
获取cell对应的模型
- parameter indexPath: 索引
- returns: 数据模型
*/
private func indexPathForSource( indexPath : NSIndexPath) -> ZKBaseModel{
var baseModel : ZKBaseModel?;
//是否分组来处理数据源
if self.isGroup {
baseModel = self.dataArray![indexPath.section][indexPath.row] as? ZKBaseModel;
}else{
baseModel = self.dataArray![indexPath.row] as? ZKBaseModel;
}
return baseModel!;
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03669-swift-sourcemanager-getmessage.swift | 11 | 286 | // 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 g: AnyObject) {
struct B<j : b { func a<f : a<T : b { func b
C([Void{
class
case c,
protocol c {
str
| mit |
ello/ello-ios | Sources/Controllers/Stream/Cells/StreamSeeMoreCommentsCell.swift | 1 | 506 | ////
/// StreamSeeMoreCommentsCell.swift
//
class StreamSeeMoreCommentsCell: CollectionViewCell {
static let reuseIdentifier = "StreamSeeMoreCommentsCell"
@IBOutlet weak var buttonContainer: UIView!
@IBOutlet weak var seeMoreButton: UIButton!
override func style() {
buttonContainer.backgroundColor = .greyA
seeMoreButton.setTitleColor(.greyA, for: .normal)
seeMoreButton.backgroundColor = .white
seeMoreButton.titleLabel?.font = .defaultFont()
}
}
| mit |
yichizhang/YZLibrary | YZLibraryDemo/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift | 55 | 4255 | import Foundation
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty<S: SequenceType>() -> NonNilMatcherFunc<S> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualSeq = try actualExpression.evaluate()
if actualSeq == nil {
return true
}
var generator = actualSeq!.generate()
return generator.next() == nil
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<String> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = try actualExpression.evaluate()
return actualString == nil || NSString(string: actualString!).length == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For NSString instances, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSString> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = try actualExpression.evaluate()
return actualString == nil || actualString!.length == 0
}
}
// Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray,
// etc, since they conform to SequenceType as well as NMBCollection.
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSDictionary> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualDictionary = try actualExpression.evaluate()
return actualDictionary == nil || actualDictionary!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSArray> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualArray = try actualExpression.evaluate()
return actualArray == nil || actualArray!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NMBCollection> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actual = try actualExpression.evaluate()
return actual == nil || actual!.count == 0
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beEmptyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
failureMessage.postfixMessage = "be empty"
if let value = actualValue as? NMBCollection {
let expr = Expression(expression: ({ value as NMBCollection }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let actualValue = actualValue {
failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSDictionaries, NSHashTables, and NSStrings)"
failureMessage.actualValue = "\(classAsString(actualValue.dynamicType)) type"
}
return false
}
}
}
#endif
| mit |
AliSoftware/Dip | Sources/AutoWiring.swift | 2 | 3528 | //
// Dip
//
// Copyright (c) 2015 Olivier Halligon <olivier@halligon.net>
//
// 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.
//
protocol AutoWiringDefinition: DefinitionType {
var numberOfArguments: Int { get }
var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> Any)? { get }
}
extension DependencyContainer {
/// Tries to resolve instance using auto-wiring
func autowire<T>(key aKey: DefinitionKey) throws -> T {
let key = aKey
guard key.typeOfArguments == Void.self else {
throw DipError.definitionNotFound(key: key)
}
let autoWiringKey = try autoWiringDefinition(byKey: key).key
do {
let key = autoWiringKey.tagged(with: key.tag ?? context.tag)
return try _resolve(key: key) { definition in
try definition.autoWiringFactory!(self, key.tag) as! T
}
}
catch {
throw DipError.autoWiringFailed(type: key.type, underlyingError: error)
}
}
private func autoWiringDefinition(byKey key: DefinitionKey) throws -> KeyDefinitionPair {
do {
return try autoWiringDefinition(byKey: key, strictByTag: true)
} catch {
if key.tag != nil {
return try autoWiringDefinition(byKey: key, strictByTag: false)
} else {
throw error
}
}
}
private func autoWiringDefinition(byKey key: DefinitionKey, strictByTag: Bool) throws -> KeyDefinitionPair {
var definitions = self.definitions.map({ (key: $0.0, definition: $0.1) })
definitions = filter(definitions: definitions, byKey: key, strictByTag: strictByTag)
definitions = definitions.sorted(by: { $0.definition.numberOfArguments > $1.definition.numberOfArguments })
guard definitions.count > 0 && definitions[0].definition.numberOfArguments > 0 else {
throw DipError.definitionNotFound(key: key)
}
let maximumNumberOfArguments = definitions.first?.definition.numberOfArguments
definitions = definitions.filter({ $0.definition.numberOfArguments == maximumNumberOfArguments })
//when there are several definitions with the same number of arguments but different arguments types
if definitions.count > 1 && definitions[0].key.typeOfArguments != definitions[1].key.typeOfArguments {
let error = DipError.ambiguousDefinitions(type: key.type, definitions: definitions.map({ $0.definition }))
throw DipError.autoWiringFailed(type: key.type, underlyingError: error)
} else {
return definitions[0]
}
}
}
| mit |
scotlandyard/expocity | expocity/Test/Firebase/Database/Models/TFDatabaseModelUser.swift | 1 | 2362 | import XCTest
@testable import expocity
class TFDatabaseModelUser:XCTestCase
{
private let kSnapshot:[String:Any] = [
"created":1475541121.581116,
"name":"John Test",
"rooms":[
"12345",
"67890",
"34567"
]
]
//MARK: -
func testModelJson()
{
let name:String = kSnapshot["name"] as! String
let nameKey:String = FDatabaseModelUser.Property.name.rawValue
let createdKey:String = FDatabaseModelUser.Property.created.rawValue
let roomsKey:String = FDatabaseModelUser.Property.rooms.rawValue
let firebaseUser:FDatabaseModelUser = FDatabaseModelUser(
name:name)
let json:Any = firebaseUser.modelJson()
let jsonDict:[String:Any]? = json as? [String:Any]
let userName:String? = jsonDict?[nameKey] as? String
let userCreated:TimeInterval? = jsonDict?[createdKey] as? TimeInterval
let userRooms:[String]? = jsonDict?[roomsKey] as? [String]
XCTAssertEqual(name, userName, "Invalid name")
XCTAssertNotNil(userCreated, "Not storing user creation timestamp")
XCTAssertGreaterThan(userCreated!, 1, "Invalid timestamp")
XCTAssertNotNil(userRooms, "Invalid user rooms")
}
func testSnapshot()
{
let snapshotName:String = kSnapshot["name"] as! String
let snapshotCreated:TimeInterval = kSnapshot["created"] as! TimeInterval
let snapshotRooms:[String] = kSnapshot["rooms"] as! [String]
let snapshotCountRooms:Int = snapshotRooms.count
let snapshotLastRoomId:String = snapshotRooms.last!
let firebaseUser:FDatabaseModelUser = FDatabaseModelUser(
snapshot:kSnapshot)
let userName:String = firebaseUser.name
let userCreated:TimeInterval = firebaseUser.created
let userRooms:[String] = firebaseUser.rooms.rooms
let userCountRooms:Int = userRooms.count
let userLastRoomId:String = userRooms.last!
XCTAssertEqual(userName, snapshotName, "Invalid name")
XCTAssertEqual(userCreated, snapshotCreated, "Invalid created timestamp")
XCTAssertEqual(snapshotCountRooms, userCountRooms, "Invalid rooms")
XCTAssertEqual(snapshotLastRoomId, userLastRoomId, "Invalid room id")
}
}
| mit |
EstefaniaGilVaquero/ciceIOS | App_CustomCell_Dictionary_PracticaOK/App_CustomCell_Dictionary_PracticaOK/AppDelegate.swift | 1 | 2157 | //
// AppDelegate.swift
// App_CustomCell_Dictionary_PracticaOK
//
// Created by cice on 13/6/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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 throttle down OpenGL ES frame rates. 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 inactive 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:.
}
}
| apache-2.0 |
Kawoou/KWDrawerController | DrawerController/Animator/DrawerCubicEaseAnimator.swift | 1 | 2213 | /*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
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
open class DrawerCubicEaseAnimator: DrawerTickAnimator {
// MARK: - Enum
public enum EaseType {
case easeIn
case easeOut
case easeInOut
internal func algorithm(value: Double) -> Double {
switch self {
case .easeIn:
return pow(value, 3)
case .easeOut:
return pow(value - 1, 3) + 1
case .easeInOut:
if value < 0.5 {
return 4 * pow(value, 3)
} else {
return 0.5 * pow((2 * value) - 2, 3) + 1
}
}
}
}
// MARK: - Property
open var easeType: EaseType
// MARK: - Public
open override func tick(delta: TimeInterval, duration: TimeInterval, animations: @escaping (Float)->()) {
animations(Float(easeType.algorithm(value: delta / duration)))
}
// MARK: - Lifecycle
public init(easeType: EaseType = .easeInOut) {
self.easeType = easeType
super.init()
}
}
| mit |
apple/swift | benchmark/single-source/DictionarySubscriptDefault.swift | 10 | 3376 | //===--- DictionarySubscriptDefault.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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 TestsUtils
public let benchmarks = [
BenchmarkInfo(name: "DictionarySubscriptDefaultMutation",
runFunction: run_DictionarySubscriptDefaultMutation,
tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArray",
runFunction: run_DictionarySubscriptDefaultMutationArray,
tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationOfObjects",
runFunction: run_DictionarySubscriptDefaultMutationOfObjects,
tags: [.validation, .api, .Dictionary], legacyFactor: 20),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArrayOfObjects",
runFunction:
run_DictionarySubscriptDefaultMutationArrayOfObjects,
tags: [.validation, .api, .Dictionary], legacyFactor: 20),
]
@inline(never)
public func run_DictionarySubscriptDefaultMutation(_ n: Int) {
for _ in 1...n {
var dict = [Int: Int]()
for i in 0..<10_000 {
dict[i % 100, default: 0] += 1
}
check(dict.count == 100)
check(dict[0]! == 100)
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationArray(_ n: Int) {
for _ in 1...n {
var dict = [Int: [Int]]()
for i in 0..<10_000 {
dict[i % 100, default: []].append(i)
}
check(dict.count == 100)
check(dict[0]!.count == 100)
}
}
// Hack to workaround the fact that if we attempt to increment the Box's value
// from the subscript, the compiler will just call the subscript's getter (and
// therefore not insert the instance) as it's dealing with a reference type.
// By using a mutating method in a protocol extension, the compiler is forced to
// treat this an actual mutation, so cannot call the getter.
protocol P {
associatedtype T
var value: T { get set }
}
extension P {
mutating func mutateValue(_ mutations: (inout T) -> Void) {
mutations(&value)
}
}
class Box<T : Hashable> : Hashable, P {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationOfObjects(_ n: Int) {
for _ in 1...n {
var dict = [Box<Int>: Box<Int>]()
for i in 0..<500 {
dict[Box(i % 5), default: Box(0)].mutateValue { $0 += 1 }
}
check(dict.count == 5)
check(dict[Box(0)]!.value == 100)
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationArrayOfObjects(_ n: Int) {
for _ in 1...n {
var dict = [Box<Int>: [Box<Int>]]()
for i in 0..<500 {
dict[Box(i % 5), default: []].append(Box(i))
}
check(dict.count == 5)
check(dict[Box(0)]!.count == 100)
}
}
| apache-2.0 |
rnystrom/GitHawk | Classes/Systems/LabelLayoutManager.swift | 1 | 1261 | //
// LabelLayoutManager.swift
// Freetime
//
// Created by Ryan Nystrom on 5/21/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
final class LabelLayoutManager: NSLayoutManager {
override func fillBackgroundRectArray(_ rectArray: UnsafePointer<CGRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: UIColor) {
// Get the attributes for the backgroundColor attribute
var range = charRange
let attributes = textStorage?.attributes(at: charRange.location, effectiveRange: &range)
// Ensure that this is one of our labels we're dealing with, ignore basic backgroundColor attributes
guard attributes?[MarkdownAttribute.label] != nil else {
super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color)
return
}
let rawRect = rectArray[0]
let rect = CGRect(
x: floor(rawRect.origin.x),
y: floor(rawRect.origin.y),
width: floor(rawRect.size.width),
height: floor(rawRect.size.height)
).insetBy(dx: -3, dy: 0)
UIBezierPath(roundedRect: rect, cornerRadius: Styles.Sizes.labelCornerRadius).fill()
}
}
| mit |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/Uploader/Requests/CLDUploadRequestWrapper.swift | 1 | 8224 | //
// CLDUploadRequestWrapper.swift
//
// Copyright (c) 2017 Cloudinary (http://cloudinary.com)
//
// 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
/**
A `CLDUploadRequestWrapper` object is a wrapper for instances of `CLDUploadRequest`. This is returned as a promise from
several `CLDUploader` functions, in case the actual concrete request cannot yet be created. This is also allows for multiple
concrete requests to be represented as one request. This class is used for preprocessing requests as well as uploda large requests.
*/
internal class CLDUploadRequestWrapper: CLDUploadRequest {
private var state = RequestState.started
fileprivate var requestsCount: Int!
fileprivate var totalLength: Int64!
fileprivate var requestsProgress = [CLDUploadRequest: Int64]()
fileprivate var totalProgress: Progress?
fileprivate var progressHandler: ((Progress) -> Void)?
fileprivate var requests = [CLDUploadRequest]()
fileprivate var result: CLDUploadResult?
fileprivate var error: NSError?
fileprivate let queue = DispatchQueue(label: "RequestsHandlingQueue", attributes: .concurrent)
fileprivate let closureQueue: OperationQueue = {
let operationQueue = OperationQueue()
operationQueue.name = "com.cloudinary.CLDUploadRequestWrapper"
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
return operationQueue
}()
/**
Once the count and total length of the request are known this method should be called.
Without this information the progress closures will not be called.
- parameter count: Number of inner requests expected to be added (or already added).
- parameter totalLength: Total length, in bytes, of the uploaded resource (can be spread across several inner request for `uploadLarge`)
*/
internal func setRequestsData(count: Int, totalLength: Int64?) {
self.totalLength = totalLength ?? 0
self.requestsCount = count
self.totalLength = totalLength ?? 0
self.totalProgress = Progress(totalUnitCount: self.totalLength)
}
/**
Add a requst to be part of the wrapping request.
- parameter request: An upload request to add - This is usually a concrete `CLDDefaultUploadRequest` to be part of this wrapper.
*/
internal func addRequest(_ request: CLDUploadRequest) {
queue.sync() {
guard self.state != RequestState.cancelled && self.state != RequestState.error else {
return
}
if (self.state == RequestState.suspended) {
request.suspend()
}
request.response() { result, error in
guard (self.state != RequestState.cancelled && self.state != RequestState.error) else {
return
}
if (error != nil) {
// single part error fails everything
self.state = RequestState.error
self.cancel()
self.requestDone(nil, error)
} else if self.requestsCount == 1 || (result?.done ?? false) {
// last part arrived successfully
self.state = RequestState.success
self.requestDone(result, nil)
}
}
request.progress() { innerProgress in
guard (self.state != RequestState.cancelled && self.state != RequestState.error) else {
return
}
self.requestsProgress[request] = innerProgress.completedUnitCount
if let totalProgress = self.totalProgress {
totalProgress.completedUnitCount = self.requestsProgress.values.reduce(0, +)
self.progressHandler?(totalProgress)
}
}
self.requests.append(request)
}
}
/**
This is used in case the request fails even without any inner upload request (e.g. when the preprocessing fails).
Once the error is set here it will be send once the completion closures are set.
- parameter error: The NSError to set.
*/
internal func setRequestError(_ error: NSError) {
state = RequestState.error
requestDone(nil, error)
}
fileprivate func requestDone(_ result: CLDUploadResult?, _ error: NSError?) {
self.error = error
self.result = result
requestsProgress.removeAll()
requests.removeAll()
closureQueue.isSuspended = false
}
// MARK: - Public
/**
Resume the request.
*/
open override func resume() {
queue.sync() {
state = RequestState.started
for request in requests {
request.resume()
}
}
}
/**
Suspend the request.
*/
open override func suspend() {
queue.sync() {
state = RequestState.suspended
for request in requests {
request.suspend()
}
}
}
/**
Cancel the request.
*/
open override func cancel() {
queue.sync() {
state = RequestState.cancelled
for request in requests {
request.cancel()
}
}
}
//MARK: Handlers
/**
Set a response closure to be called once the request has finished.
- parameter completionHandler: The closure to be called once the request has finished, holding either the response object or the error.
- returns: The same instance of CldUploadRequestWrapper.
*/
@discardableResult
open override func response(_ completionHandler: @escaping (_ result: CLDUploadResult?, _ error: NSError?) -> ()) -> Self {
closureQueue.addOperation {
completionHandler(self.result, self.error)
}
return self
}
/**
Set a progress closure that is called periodically during the data transfer.
- parameter progressBlock: The closure that is called periodically during the data transfer.
- returns: The same instance of CLDUploadRequestWrapper.
*/
@discardableResult
open override func progress(_ progress: @escaping ((Progress) -> Void)) -> Self {
self.progressHandler = progress
return self
}
/**
Sets a cleanup handler that is called when the request doesn't need it's resources anymore.
This is called whether the request succeeded or not.
- Parameter handler: The closure to be called once cleanup is necessary.
- returns: The same instance of CLDUploadRequestWrapper.
*/
@discardableResult
internal func cleanupHandler(handler: @escaping (_ success: Bool) -> ()) -> Self {
closureQueue.addOperation {
handler(self.state == RequestState.success)
}
return self
}
}
fileprivate enum RequestState: Int {
case started, suspended, cancelled, error, success
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/23080-swift-tupletype-get.swift | 11 | 324 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
println(1)
struct A{
let a{
deinit{
{
}
{
protocol a{
class A{
func e
{
{
protocol a{
protocol p{
let a=[{
class B{
class A{
deinit{
class
case c,
class
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/14130-resolvetypedecl.swift | 11 | 245 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b( ) {
struct B<T where g: AnyObject
let a = 1 )
enum b {
var f = B? {
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/21769-no-stacktrace.swift | 11 | 217 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
let h, f {
class
case ,
let a = == == h [
| mit |
hanhailong/practice-swift | Autolayout/BasicAutolayout/BasicAutolayoutTests/BasicAutolayoutTests.swift | 2 | 927 | //
// BasicAutolayoutTests.swift
// BasicAutolayoutTests
//
// Created by Domenico on 17.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
import XCTest
class BasicAutolayoutTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
masters3d/xswift | exercises/dominoes/Package.swift | 1 | 73 | import PackageDescription
let package = Package(
name: "Dominoes"
)
| mit |
thehung111/ViSearchSwiftSDK | Example/Example/Lib/ImageLoader/Disk.swift | 3 | 3338 | //
// Disk.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 12/21/14.
// Copyright © 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
extension String {
public func escape() -> String? {
return addingPercentEncoding(withAllowedCharacters: .alphanumerics)
}
}
public class Disk {
var storedData = [String: Data]()
class Directory {
init() {
createDirectory()
}
private func createDirectory() {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path) {
return
}
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
var path: String {
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let directoryName = "swift.imageloader.disk"
return cacheDirectory + "/" + directoryName
}
}
let directory = Directory()
fileprivate let _subscriptQueue = DispatchQueue(label: "swift.imageloader.queues.disk.subscript", attributes: .concurrent)
fileprivate let _ioQueue = DispatchQueue(label: "swift.imageloader.queues.disk.set")
}
extension Disk {
public class func cleanUp() {
Disk().cleanUp()
}
func cleanUp() {
let manager = FileManager.default
for subpath in manager.subpaths(atPath: directory.path) ?? [] {
let path = directory.path + "/" + subpath
do {
try manager.removeItem(atPath: path)
} catch _ {
}
}
}
public class func get(_ aKey: String) -> Data? {
return Disk().get(aKey)
}
public class func set(_ anObject: Data, forKey aKey: String) {
Disk().set(anObject, forKey: aKey)
}
public func get(_ aKey: String) -> Data? {
if let data = storedData[aKey] {
return data
}
return (try? Data(contentsOf: URL(fileURLWithPath: _path(aKey))))
}
fileprivate func get(_ aKey: URL) -> Data? {
guard let key = aKey.absoluteString.escape() else { return nil }
return get(key)
}
fileprivate func _path(_ name: String) -> String {
return directory.path + "/" + name
}
public func set(_ anObject: Data, forKey aKey: String) {
storedData[aKey] = anObject
let block: () -> Void = {
do {
try anObject.write(to: URL(fileURLWithPath: self._path(aKey)), options: [])
self.storedData[aKey] = nil
} catch _ {}
}
_ioQueue.async(execute: block)
}
fileprivate func set(_ anObject: Data, forKey aKey: URL) {
guard let key = aKey.absoluteString.escape() else { return }
set(anObject, forKey: key)
}
}
extension Disk: ImageLoaderCache {
public subscript (aKey: URL) -> Data? {
get {
var data : Data?
_subscriptQueue.sync {
data = self.get(aKey)
}
return data
}
set {
_subscriptQueue.async {
self.set(newValue!, forKey: aKey)
}
}
}
}
| mit |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Message/Converstaion/ChatViewModel.swift | 1 | 6784 | //
// ChatViewModel.swift
// HiPDA
//
// Created by leizh007 on 2017/7/3.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import JSQMessagesViewController
import RxSwift
import SDWebImage
enum ChatMessageType {
case incoming
case outgoing
}
class ChatViewModel {
let user: User
fileprivate var disposeBag = DisposeBag()
fileprivate var messages = [JSQMessage]()
fileprivate var avatars = [String: JSQMessagesAvatarImage]()
fileprivate var formhash = ""
fileprivate var lastdaterange = ""
fileprivate let dateFormater: DateFormatter = {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d"
return dateFormater
}()
fileprivate let secondDateFormater: DateFormatter = {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d HH:mm:ss"
return dateFormater
}()
init(user: User) {
self.user = user
}
func fetchConversation(with completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
guard let account = Settings.shared.activeAccount else {
completion(.failure(NSError(domain: "HiPDA", code: -1, userInfo: [NSLocalizedDescriptionKey: "请登录后再使用"])))
return
}
let group = DispatchGroup()
for user in [self.user, User(name: account.name, uid: account.uid)] {
group.enter()
ChatViewModel.getAvatar(of: user) { image in
self.avatars["\(user.uid)"] = JSQMessagesAvatarImageFactory.avatarImage(withPlaceholder: image, diameter: UInt(max(image.size.width, image.size.height) / C.UI.screenScale))
group.leave()
}
}
var event: (Event<[JSQMessage]>)!
group.enter()
disposeBag = DisposeBag()
HiPDAProvider.request(.privateMessageConversation(uid: user.uid))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive))
.mapGBKString()
.do(onNext: { [weak self] html in
self?.formhash = try HtmlParser.replyValue(for: "formhash", in: html)
self?.lastdaterange = try HtmlParser.replyValue(for: "lastdaterange", in: html)
})
.map { try HtmlParser.chatMessges(from: $0).map(self.transform(message:)) }
.observeOn(MainScheduler.instance)
.subscribe { e in
switch e {
case .next(_):
fallthrough
case .error(_):
event = e
group.leave()
default:
break
}
}.disposed(by: disposeBag)
group.notify(queue: DispatchQueue.main) {
switch event! {
case .next(let messages):
self.messages = messages
completion(.success(()))
case .error(let error):
completion(.failure(error as NSError))
default:
break
}
}
}
private static func getAvatar(of user: User, completion: @escaping (UIImage) -> Void) {
SDWebImageManager.shared().loadImage(with: user.avatarImageURL, options: [], progress: nil) { (image, _, _, _, _, _) in
if let image = image {
completion(image)
} else {
completion(#imageLiteral(resourceName: "avatar_placeholder"))
}
}
}
private func transform(message: ChatMessage) -> JSQMessage {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d HH:mm"
let date = dateFormater.date(from: message.time) ?? Date()
let senderId = message.name == user.name ? user.uid : (Settings.shared.activeAccount?.uid ?? 0)
return JSQMessage(senderId: "\(senderId)", senderDisplayName: message.name, date: date, text: message.content)
}
fileprivate func dateString(of date: Date) -> String {
return dateFormater.string(from: date)
}
func sendMessage(_ message: JSQMessage, with completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
messages.append(message)
HiPDAProvider.request(.replypm(uid: user.uid, formhash: formhash, lastdaterange: lastdaterange, message: message.text ?? ""))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive))
.mapGBKString()
.map { html -> Bool in
let messages = try HtmlParser.chatMessges(from: html)
if messages.count == 1 && messages[0].content == message.text {
return true
}
let result = try Regex.firstMatch(in: html, of: "\\[CDATA\\[([^<]+)<")
if result.count == 2 && !result[1].isEmpty {
throw HtmlParserError.underlying("发送失败: \(result[1])")
} else {
throw HtmlParserError.underlying("发送失败")
}
}
.observeOn(MainScheduler.instance)
.subscribe { [weak self] event in
guard let `self` = self else { return }
switch event {
case .next(_):
completion(.success(()))
case .error(let error):
self.messages = self.messages.filter { self.secondDateFormater.string(from: $0.date) != self.secondDateFormater.string(from: message.date) }
completion(.failure(error as NSError))
default:
break
}
}.disposed(by: disposeBag)
}
}
// MARK: - DataSource
extension ChatViewModel {
func numberOfItems() -> Int {
return messages.count
}
func message(at index: Int) -> JSQMessage {
return messages[index]
}
func avatar(at index: Int) -> JSQMessagesAvatarImage? {
return avatars[message(at: index).senderId]
}
func messageType(at index: Int) -> ChatMessageType {
return message(at: index).senderId == "\(user.uid)" ? .incoming : .outgoing
}
func user(at index: Int) -> User {
switch messageType(at: index) {
case .incoming:
return user
case .outgoing:
return User(name: Settings.shared.activeAccount?.name ?? "", uid: Settings.shared.activeAccount?.uid ?? 0)
}
}
func shouldShowCellTopLabel(at index: Int) -> Bool {
if index == 0 {
return true
}
return dateString(at: index - 1) != dateString(at: index)
}
func dateString(at index: Int) -> String {
return dateString(of: message(at: index).date)
}
}
| mit |
rc2server/appserverSwift | Sources/Rc2AppServer/InfoHandler.swift | 1 | 1029 | //
// InfoHandler.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import PerfectHTTP
import PerfectLib
import Rc2Model
class InfoHandler: BaseHandler {
func routes() -> [Route] {
var routes = [Route]()
routes.append(Route(method: .get, uri: settings.config.urlPrefixToIgnore + "/info", handler: getBulkInfo))
return routes
}
// return bulk info for logged in user
func getBulkInfo(request: HTTPRequest, response: HTTPResponse) {
do {
guard let userId = request.login?.userId,
let user = try settings.dao.getUser(id: userId)
else {
handle(error: SessionError.invalidRequest, response: response)
return
}
let bulkInfo = try settings.dao.getUserInfo(user: user)
response.bodyBytes.removeAll()
response.bodyBytes.append(contentsOf: try settings.encode(bulkInfo))
response.setHeader(.contentType, value: MimeType.forExtension("json"))
response.completed()
} catch {
response.completed(status: .notFound)
}
}
}
| isc |
galv/reddift | reddiftSample/BaseSubredditsViewController.swift | 2 | 744 | //
// BaseSubredditsViewController.swift
// reddift
//
// Created by sonson on 2015/05/04.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class BaseSubredditsViewController: UITableViewController, UISearchBarDelegate {
var session:Session? = nil
var paginator:Paginator? = Paginator()
var loading = false
var task:NSURLSessionDataTask? = nil
var segmentedControl:UISegmentedControl? = nil
var sortTitles:[String] = []
var sortTypes:[SubredditsWhere] = []
var subreddits:[Subreddit] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
}
| mit |
crewshin/GasLog | Pods/Material/Sources/MaterialRadius.swift | 2 | 2168 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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
public enum MaterialRadius {
case None
case Radius1
case Radius2
case Radius3
case Radius4
case Radius5
case Radius6
case Radius7
case Radius8
case Radius9
}
/**
:name: MaterialRadiusToValue
*/
public func MaterialRadiusToValue(radius: MaterialRadius) -> CGFloat {
switch radius {
case .None:
return 0
case .Radius1:
return 4
case .Radius2:
return 8
case .Radius3:
return 16
case .Radius4:
return 24
case .Radius5:
return 32
case .Radius6:
return 40
case .Radius7:
return 48
case .Radius8:
return 56
case .Radius9:
return 64
}
}
| mit |
plutoless/fgo-pluto | FgoPluto/FgoPluto/model/BaseObject.swift | 1 | 316 | //
// BaseObject.swift
// FgoPluto
//
// Created by Zhang, Qianze on 17/09/2017.
// Copyright © 2017 Plutoless Studio. All rights reserved.
//
import Foundation
import RealmSwift
import Realm
class BaseObject : Object{
internal func fillvalues(realm:Realm, data:[String:AnyObject]){
}
}
| apache-2.0 |
DingSoung/CCExtension | Sources/Swift/String+regex.swift | 2 | 1573 | // Created by Songwen Ding on 2017/8/3.
// Copyright © 2017年 DingSoung. All rights reserved.
#if canImport(Foundation)
import Foundation.NSRegularExpression
infix operator =~: AdditionPrecedence
private struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
}
func match(input: String) -> Bool {
let matches = regex.matches(in: input,
options: [],
range: NSRange(location: 0, length: input.utf16.count))
return matches.count > 0
}
}
extension String {
static func =~ (str: String, regex: String) -> Bool {
do {
return try RegexHelper(regex).match(input: str as String)
} catch _ {
return false
}
}
public func match(regex: String) -> Bool {
return self =~ regex
}
}
extension String {
/// check is mobile phone number
public var isPRCMobileNumber: Bool {
//前缀0 86 17951 或者没有 中间13* 15* 17* 145 147 后加8个0~9的数
return self =~ "^(0|86|086|17951)?1(3[0-9]|4[57]|7[0-9]|8[0123456789])[0-9]{8}$"
}
/// check is ID if People's Republic of China
public var isPRCIDNumber: Bool {
return self =~ "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"
|| self =~ "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2))(([0|1|2]\\d)|2[0-1])\\d{4}$"
}
}
#endif
| mit |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCAccountTableViewCell.swift | 2 | 19492 | //
// NCAccountTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 13.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCAccountTableViewCell: NCTableViewCell {
@IBOutlet weak var characterNameLabel: UILabel?
@IBOutlet weak var characterImageView: UIImageView?
@IBOutlet weak var corporationLabel: UILabel?
@IBOutlet weak var spLabel: UILabel?
@IBOutlet weak var wealthLabel: UILabel?
@IBOutlet weak var locationLabel: UILabel?
// @IBOutlet weak var subscriptionLabel: UILabel!
@IBOutlet weak var skillLabel: UILabel?
@IBOutlet weak var trainingTimeLabel: UILabel?
@IBOutlet weak var skillQueueLabel: UILabel?
@IBOutlet weak var trainingProgressView: UIProgressView?
@IBOutlet weak var alertLabel: UILabel?
var progressHandler: NCProgressHandler?
override func awakeFromNib() {
super.awakeFromNib()
let layer = self.trainingProgressView?.superview?.layer;
layer?.borderColor = UIColor(number: 0x3d5866ff).cgColor
layer?.borderWidth = 1.0 / UIScreen.main.scale
}
}
extension Prototype {
enum NCAccountTableViewCell {
static let `default` = Prototype(nib: UINib(nibName: "NCAccountTableViewCell", bundle: nil), reuseIdentifier: "NCAccountTableViewCell")
}
}
class NCAccountsNode<Row: NCAccountRow>: TreeNode {
let cachePolicy: URLRequest.CachePolicy
init(context: NSManagedObjectContext, cachePolicy: URLRequest.CachePolicy) {
self.cachePolicy = cachePolicy
super.init()
let defaultAccounts: FetchedResultsNode<NCAccount> = {
let request = NSFetchRequest<NCAccount>(entityName: "Account")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true),
NSSortDescriptor(key: "characterName", ascending: true)]
request.predicate = NSPredicate(format: "folder == nil", "")
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return FetchedResultsNode(resultsController: results, objectNode: Row.self)
}()
let folders: FetchedResultsNode<NCAccountsFolder> = {
let request = NSFetchRequest<NCAccountsFolder>(entityName: "AccountsFolder")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return FetchedResultsNode(resultsController: results, objectNode: NCAccountsFolderSection<Row>.self)
}()
children = [DefaultTreeSection(prototype: Prototype.NCHeaderTableViewCell.default, nodeIdentifier: "Default", title: NSLocalizedString("Default", comment: "").uppercased(), children: [defaultAccounts]), folders]
}
}
class NCAccountsFolderSection<Row: NCAccountRow>: NCFetchedResultsObjectNode<NCAccountsFolder>, CollapseSerializable {
var collapseState: NCCacheSectionCollapse?
var collapseIdentifier: String? {
return self.object.objectID.uriRepresentation().absoluteString
}
required init(object: NCAccountsFolder) {
super.init(object: object)
isExpandable = true
cellIdentifier = Prototype.NCHeaderTableViewCell.default.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCHeaderTableViewCell else {return}
cell.titleLabel?.text = (object.name?.isEmpty == false ? object.name : NSLocalizedString("Unnamed", comment: ""))?.uppercased()
}
override func loadChildren() {
guard let context = object.managedObjectContext else {return}
let request = NSFetchRequest<NCAccount>(entityName: "Account")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true),
NSSortDescriptor(key: "characterName", ascending: true)]
request.predicate = NSPredicate(format: "folder == %@", object)
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
children = [FetchedResultsNode(resultsController: results, objectNode: Row.self)]
}
override func willMoveToTreeController(_ treeController: TreeController?) {
if let collapseState = getCollapseState() {
isExpanded = collapseState.isExpanded
self.collapseState = collapseState
}
else {
self.collapseState = nil
}
super.willMoveToTreeController(treeController)
}
override var isExpanded: Bool {
didSet {
collapseState?.isExpanded = isExpanded
}
}
}
class NCAccountRow: NCFetchedResultsObjectNode<NCAccount> {
private struct LoadingOptions: OptionSet {
var rawValue: Int
static let characterInfo = LoadingOptions(rawValue: 1 << 0)
static let corporationInfo = LoadingOptions(rawValue: 1 << 1)
static let skillQueue = LoadingOptions(rawValue: 1 << 2)
static let skills = LoadingOptions(rawValue: 1 << 3)
static let walletBalance = LoadingOptions(rawValue: 1 << 4)
static let characterLocation = LoadingOptions(rawValue: 1 << 5)
static let characterShip = LoadingOptions(rawValue: 1 << 6)
static let image = LoadingOptions(rawValue: 1 << 7)
var count: Int {
return sequence(first: rawValue) {$0 > 1 ? $0 >> 1 : nil}.reduce(0) {
$0 + (($1 & 1) == 1 ? 1 : 0)
}
}
}
required init(object: NCAccount) {
super.init(object: object)
canMove = true
cellIdentifier = Prototype.NCAccountTableViewCell.default.reuseIdentifier
}
var cachePolicy: URLRequest.CachePolicy {
var parent = self.parent
while parent != nil && !(parent is NCAccountsNode) {
parent = parent?.parent
}
return (parent as? NCAccountsNode)?.cachePolicy ?? .useProtocolCachePolicy
}
lazy var dataManager: NCDataManager = {
return NCDataManager(account: self.object, cachePolicy: self.cachePolicy)
}()
var character: Future<CachedValue<ESI.Character.Information>>?
var corporation: Future<CachedValue<ESI.Corporation.Information>>?
var skillQueue: Future<CachedValue<[ESI.Skills.SkillQueueItem]>>?
var walletBalance: Future<CachedValue<Double>>?
var skills: Future<CachedValue<ESI.Skills.CharacterSkills>>?
var location: Future<CachedValue<ESI.Location.CharacterLocation>>?
var ship: Future<CachedValue<ESI.Location.CharacterShip>>?
var image: Future<CachedValue<UIImage>>?
var isLoaded = false
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCAccountTableViewCell else {return}
cell.object = object
if !isLoaded {
var options = LoadingOptions()
if cell.corporationLabel != nil {
options.insert(.characterInfo)
options.insert(.corporationInfo)
}
if cell.skillQueueLabel != nil {
options.insert(.skillQueue)
}
if cell.skillLabel != nil {
options.insert(.skills)
}
if cell.wealthLabel != nil {
options.insert(.walletBalance)
}
if cell.locationLabel != nil{
options.insert(.characterLocation)
options.insert(.characterShip)
}
if cell.imageView != nil {
options.insert(.image)
}
_ = reload(options: options)
isLoaded = true
}
configureImage(cell: cell)
configureSkills(cell: cell)
configureWallets(cell: cell)
configureLocation(cell: cell)
configureCharacter(cell: cell)
configureSkillQueue(cell: cell)
configureCorporation(cell: cell)
if object.isInvalid {
cell.alertLabel?.isHidden = true
}
else {
if let scopes = object.scopes?.compactMap({($0 as? NCScope)?.name}), Set(ESI.Scope.default.map{$0.rawValue}).isSubset(of: Set(scopes)) {
cell.alertLabel?.isHidden = true
}
else {
cell.alertLabel?.isHidden = false
}
}
}
func configureCharacter(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.characterNameLabel?.text = object.characterName
}
else {
cell.characterNameLabel?.text = " "
character?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.characterNameLabel?.text = result.value?.name ?? " "
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.characterNameLabel?.text = error.localizedDescription
}
}
}
func configureCorporation(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.corporationLabel?.text = NSLocalizedString("Access Token did become invalid", comment: "")
cell.corporationLabel?.textColor = .red
}
else {
cell.corporationLabel?.textColor = .white
cell.corporationLabel?.text = " "
corporation?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.corporationLabel?.text = result.value?.name ?? " "
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.corporationLabel?.text = error.localizedDescription
}
}
}
func configureSkillQueue(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.skillLabel?.text = " "
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
}
else {
cell.skillLabel?.text = " "
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
skillQueue?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let value = result.value else {return}
let date = Date()
let skillQueue = value.filter {
guard let finishDate = $0.finishDate else {return false}
return finishDate >= date
}
let firstSkill = skillQueue.first { $0.finishDate! > date }
let trainingTime: String
let trainingProgress: Float
let title: NSAttributedString
if let skill = firstSkill {
guard let type = NCDatabase.sharedDatabase?.invTypes[skill.skillID] else {return}
guard let firstTrainingSkill = NCSkill(type: type, skill: skill) else {return}
if !firstTrainingSkill.typeName.isEmpty {
title = NSAttributedString(skillName: firstTrainingSkill.typeName, level: 1 + (firstTrainingSkill.level ?? 0))
}
else {
title = NSAttributedString(string: String(format: NSLocalizedString("Unknown skill %d", comment: ""), firstTrainingSkill.typeID))
}
trainingProgress = firstTrainingSkill.trainingProgress
if let endTime = firstTrainingSkill.trainingEndDate {
trainingTime = NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes)
}
else {
trainingTime = " "
}
}
else {
title = NSAttributedString(string: NSLocalizedString("No skills in training", comment: ""), attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText])
trainingProgress = 0
trainingTime = " "
}
let skillQueueText: String
if let skill = skillQueue.last, let endTime = skill.finishDate {
skillQueueText = String(format: NSLocalizedString("%d skills in queue (%@)", comment: ""), skillQueue.count, NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes))
}
else {
skillQueueText = " "
}
cell.skillLabel?.attributedText = title
cell.trainingTimeLabel?.text = trainingTime
cell.trainingProgressView?.progress = trainingProgress
cell.skillQueueLabel?.text = skillQueueText
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.skillLabel?.text = error.localizedDescription
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
}
}
}
func configureWallets(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.wealthLabel?.text = " "
}
else {
cell.wealthLabel?.text = " "
walletBalance?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let wealth = result.value else {return}
cell.wealthLabel?.text = NCUnitFormatter.localizedString(from: wealth, unit: .none, style: .short)
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.wealthLabel?.text = error.localizedDescription
}
}
}
func configureSkills(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.spLabel?.text = " "
}
else {
cell.spLabel?.text = " "
skills?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let value = result.value else {return}
cell.spLabel?.text = NCUnitFormatter.localizedString(from: Double(value.totalSP), unit: .none, style: .short)
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.spLabel?.text = error.localizedDescription
}
}
}
func configureLocation(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.locationLabel?.text = " "
}
else {
all(
self.location?.then(on: .main) { result -> String? in
guard let value = result.value else {return nil}
guard let solarSystem = NCDatabase.sharedDatabase?.mapSolarSystems[value.solarSystemID] else {return nil}
return "\(solarSystem.solarSystemName!) / \(solarSystem.constellation!.region!.regionName!)"
} ?? .init(nil),
self.ship?.then(on: .main) { result -> String? in
guard let value = result.value else {return nil}
guard let type = NCDatabase.sharedDatabase?.invTypes[value.shipTypeID] else {return nil}
return type.typeName
} ?? .init(nil)
).then(on: .main) { (location, ship) in
guard cell.object as? NCAccount == self.object else {return}
if let ship = ship, let location = location {
let s = NSMutableAttributedString()
s.append(NSAttributedString(string: ship, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]))
s.append(NSAttributedString(string: ", \(location)", attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText]))
cell.locationLabel?.attributedText = s
}
else if let location = location {
let s = NSAttributedString(string: location, attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText])
cell.locationLabel?.attributedText = s
}
else if let ship = ship {
let s = NSAttributedString(string: ship, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
cell.locationLabel?.attributedText = s
}
else {
cell.locationLabel?.text = " "
}
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.locationLabel?.text = error.localizedDescription
}
}
}
func configureImage(cell: NCAccountTableViewCell) {
cell.characterImageView?.image = UIImage()
image?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.characterImageView?.image = result.value
}
}
private var observer: NCManagedObjectObserver?
private var isLoading: Bool = false
private func reconfigure() {
// guard let cell = self.treeController?.cell(for: self) else {return}
// self.configure(cell: cell)
}
private func reload(options: LoadingOptions) -> Future<Void> {
guard !isLoading else {
return .init(())
}
isLoading = true
if object.isInvalid {
image = dataManager.image(characterID: object.characterID, dimension: 64)
image?.then(on: .main) { result in
self.reconfigure()
self.isLoading = false
}
return .init(())
}
else {
observer = NCManagedObjectObserver() { [weak self] (updated, deleted) in
guard let strongSelf = self else {return}
strongSelf.reconfigure()
}
let dataManager = self.dataManager
let cell = treeController?.cell(for: self)
let progress = cell != nil ? NCProgressHandler(view: cell!, totalUnitCount: Int64(options.count)) : nil
var queue = [Future<Void>]()
if options.contains(.characterInfo) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
character = dataManager.character()
progress?.progress.resignCurrent()
queue.append(
character!.then(on: .main) { result -> Future<Void> in
guard let value = result.value else {throw NCDataManagerError.noCacheData}
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
if options.contains(.corporationInfo) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
self.corporation = dataManager.corporation(corporationID: Int64(value.corporationID))
progress?.progress.resignCurrent()
return self.corporation!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
}
}
else {
return .init(())
}
})
}
if options.contains(.skillQueue) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
skillQueue = dataManager.skillQueue()
progress?.progress.resignCurrent()
queue.append(
skillQueue!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.skills) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
skills = dataManager.skills()
progress?.progress.resignCurrent()
queue.append(
skills!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.walletBalance) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
walletBalance = dataManager.walletBalance()
progress?.progress.resignCurrent()
queue.append(
walletBalance!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
}
)
}
if options.contains(.characterLocation) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
location = dataManager.characterLocation()
progress?.progress.resignCurrent()
queue.append(
location!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.characterShip) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
ship = dataManager.characterShip()
progress?.progress.resignCurrent()
queue.append(
ship!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.image) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
image = dataManager.image(characterID: object.characterID, dimension: 64)
progress?.progress.resignCurrent()
queue.append(
image!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
return all(queue).then { _ -> Void in
}.finally(on: .main) {
progress?.finish()
self.isLoading = false
guard let cell = self.treeController?.cell(for: self) else {return}
self.configure(cell: cell)
}
}
}
}
| lgpl-2.1 |
almazrafi/Metatron | Sources/ID3v2/FrameStuffs/ID3v2Comments.swift | 1 | 2024 | //
// ID3v2Comments.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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 class ID3v2Comments: ID3v2LocalizedText {
}
public class ID3v2CommentsFormat: ID3v2FrameStuffSubclassFormat {
// MARK: Type Properties
public static let regular = ID3v2CommentsFormat()
// MARK: Instance Methods
public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2Comments {
return ID3v2Comments(fromData: data, version: version)
}
public func createStuffSubclass(fromOther other: ID3v2Comments) -> ID3v2Comments {
let stuff = ID3v2Comments()
stuff.textEncoding = other.textEncoding
stuff.language = other.language
stuff.description = other.description
stuff.content = other.content
return stuff
}
public func createStuffSubclass() -> ID3v2Comments {
return ID3v2Comments()
}
}
| mit |
RedRoma/Lexis | Code/Lexis/URLs+.swift | 1 | 1153 | //
// URLs+.swift
// Lexis
//
// Created by Wellington Moreno on 9/25/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import Archeota
extension URL
{
var string: String? { return downloadToString() }
var data: Data? { return downloadToData() }
func downloadToString() -> String?
{
do
{
return try String(contentsOf: self)
}
catch
{
LOG.error("Failed to download string from \(self): \(error)")
return nil
}
}
func downloadToData() -> Data?
{
do
{
return try Data(contentsOf: self)
}
catch
{
LOG.error("Failed to download data from \(self): \(error)")
return nil
}
}
func downloadToImage() -> UIImage?
{
guard let data = downloadToData() else { return nil }
if let image = UIImage(data: data)
{
return image
}
else
{
LOG.error("Failed to download image from: \(self)")
return nil
}
}
}
| apache-2.0 |
stephentyrone/swift | test/AutoDiff/Serialization/transpose_attr.swift | 3 | 2276 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -emit-module -parse-as-library -o %t
// RUN: llvm-bcanalyzer %t/transpose_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-sil-opt -disable-sil-linking -enable-sil-verify-all %t/transpose_attr.swiftmodule -o - | %FileCheck %s
// BCANALYZER-NOT: UnknownCode
import _Differentiation
// Dummy `Differentiable`-conforming type.
struct S: Differentiable & AdditiveArithmetic {
static var zero: S { S() }
static func + (_: S, _: S) -> S { S() }
static func - (_: S, _: S) -> S { S() }
typealias TangentVector = S
}
// Test top-level functions.
func top1(_ x: S) -> S {
x
}
// CHECK: @transpose(of: top1, wrt: 0)
@transpose(of: top1, wrt: 0)
func transposeTop1(v: S) -> S {
v
}
func top2<T, U>(_ x: T, _ i: Int, _ y: U) -> U {
y
}
// CHECK: @transpose(of: top2, wrt: (0, 2))
@transpose(of: top2, wrt: (0, 2))
func transposeTop2<T, U>(_ int: Int, v: U) -> (T, U)
where T: Differentiable, U: Differentiable,
T == T.TangentVector, U == U.TangentVector {
(.zero, v)
}
// Test instance methods.
extension S {
func instanceMethod(_ other: S) -> S {
self + other
}
// CHECK: @transpose(of: instanceMethod, wrt: 0)
@transpose(of: instanceMethod, wrt: 0)
func transposeInstanceMethod(t: S) -> S {
self + t
}
// CHECK: @transpose(of: instanceMethod, wrt: self)
@transpose(of: instanceMethod, wrt: self)
static func transposeInstanceMethodWrtSelf(_ other: S, t: S) -> S {
other + t
}
}
// Test static methods.
extension S {
static func staticMethod(x: S) -> S {
x
}
// CHECK: @transpose(of: staticMethod, wrt: 0)
@transpose(of: staticMethod, wrt: 0)
static func transposeStaticMethod(t: S) -> S {
t
}
}
// Test computed properties.
extension S {
var computedProperty: S { self }
// CHECK: @transpose(of: computedProperty, wrt: self)
@transpose(of: computedProperty, wrt: self)
static func transposeProperty(t: Self) -> Self {
t
}
}
// Test subscripts.
extension S {
subscript<T: Differentiable>(x: T) -> Self { self }
// CHECK: @transpose(of: subscript, wrt: self)
@transpose(of: subscript(_:), wrt: self)
static func transposeSubscript<T: Differentiable>(x: T, t: Self) -> Self {
t
}
}
| apache-2.0 |
dvxiaofan/Pro-Swift-Learning | Part-02/01-RepeatingValues.playground/Contents.swift | 1 | 339 | //: Playground - noun: a place where people can play
import UIKit
let headeing = "This is a heading"
let underline = String(repeating: "=", count: headeing.characters.count)
let equalsArray = [String](repeating: "=", count: headeing.characters.count)
var board = [[String]](repeating: [String](repeating: "", count: 10), count: 10)
| mit |
Spriter/SwiftyHue | Sources/Base/BridgeResourceModels/Sensors/TemperatureSensor/TemperatureSensor.swift | 1 | 1890 | //
// TemperatureSensor.swift
// Pods
//
// Created by Jerome Schmitz on 01.05.16.
//
//
import Foundation
import Gloss
public class TemperatureSensor: PartialSensor {
let config: TemperatureSensorConfig
let state: TemperatureSensorState
required public init?(sensor: Sensor) {
guard let sensorConfig = sensor.config else {
return nil
}
guard let sensorState = sensor.state else {
return nil
}
guard let config: TemperatureSensorConfig = TemperatureSensorConfig(sensorConfig: sensorConfig) else {
return nil
}
guard let state: TemperatureSensorState = TemperatureSensorState(state: sensorState) else {
return nil
}
self.config = config
self.state = state
super.init(identifier: sensor.identifier, uniqueId: sensor.uniqueId, name: sensor.name, type: sensor.type, modelId: sensor.modelId, manufacturerName: sensor.manufacturerName, swVersion: sensor.swVersion, recycle: sensor.recycle)
}
public required init?(json: JSON) {
guard let config: TemperatureSensorConfig = "config" <~~ json else {
return nil
}
guard let state: TemperatureSensorState = "state" <~~ json else {
return nil
}
self.config = config
self.state = state
super.init(json: json)
}
}
public func ==(lhs: TemperatureSensor, rhs: TemperatureSensor) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.name == rhs.name &&
lhs.state == rhs.state &&
lhs.config == rhs.config &&
lhs.type == rhs.type &&
lhs.modelId == rhs.modelId &&
lhs.manufacturerName == rhs.manufacturerName &&
lhs.swVersion == rhs.swVersion
}
| mit |
mrchenhao/Queue | Queue/QueueTask.swift | 1 | 7830 | //
// QueueTask.swift
// Queue
//
// Created by ChenHao on 12/10/15.
// Copyright © 2015 HarriesChen. All rights reserved.
//
import Foundation
public typealias TaskCallBack = (QueueTask) -> Void
public typealias TaskCompleteCallback = (QueueTask, Error?) -> Void
public typealias JSONDictionary = [String: Any]
// swiftlint:disable line_length
// swiftlint:disable variable_name
open class QueueTask: Operation {
public let queue: Queue
open var taskID: String
open var taskType: String
open var retries: Int
public let created: Date
open var started: Date?
open var userInfo: Any?
var error: Error?
var _executing: Bool = false
var _finished: Bool = false
open override var name: String? {
get {
return taskID
}
set {
}
}
open override var isExecuting: Bool {
get { return _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
open override var isFinished: Bool {
get { return _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
// MARK: - Init
/**
Initializes a new QueueTask with following paramsters
- parameter queue: the queue the execute the task
- parameter taskID: A unique identifer for the task
- parameter taskType: A type that will be used to group tasks together, tasks have to be generic with respect to their type
- parameter userInfo: other infomation
- parameter created: When the task was created
- parameter started: When the task was started first time
- parameter retries: Number of times this task has been retries after failing
- returns: A new QueueTask
*/
fileprivate init(queue: Queue, taskID: String? = nil, taskType: String, userInfo: Any? = nil,
created: Date = Date(), started: Date? = nil ,
retries: Int = 0) {
self.queue = queue
self.taskID = taskID ?? UUID().uuidString
self.taskType = taskType
self.retries = retries
self.created = created
self.userInfo = userInfo
super.init()
}
public convenience init(queue: Queue, type: String, userInfo: Any? = nil, retries: Int = 0) {
self.init(queue: queue, taskType: type, userInfo: userInfo, retries: retries)
}
public convenience init?(dictionary: JSONDictionary, queue: Queue) {
if let taskID = dictionary["taskID"] as? String,
let taskType = dictionary["taskType"] as? String,
let data = dictionary["userInfo"],
let createdStr = dictionary["created"] as? String,
let startedStr = dictionary["started"] as? String,
let retries = dictionary["retries"] as? Int? ?? 0 {
let created = Date(dateString: createdStr) ?? Date()
let started = Date(dateString: startedStr)
self.init(queue: queue, taskID: taskID, taskType: taskType, userInfo: data, created: created,
started: started, retries: retries)
} else {
self.init(queue: queue, taskID: "", taskType: "")
return nil
}
}
public convenience init?(json: String, queue: Queue) {
do {
if let dict = try fromJSON(json) as? [String: Any] {
self.init(dictionary: dict, queue: queue)
} else {
return nil
}
} catch {
return nil
}
}
open func toJSONString() -> String? {
let dict = toDictionary()
let nsdict = NSMutableDictionary(capacity: dict.count)
for (key, value) in dict {
nsdict[key] = value ?? NSNull()
}
do {
let json = try toJSON(nsdict)
return json
} catch {
return nil
}
}
open func toDictionary() -> [String: Any?] {
var dict = [String: Any?]()
dict["taskID"] = self.taskID
dict["taskType"] = self.taskType
dict["created"] = self.created.toISOString()
dict["retries"] = self.retries
dict["userInfo"] = self.userInfo
if let started = self.started {
dict["started"] = started.toISOString()
}
return dict
}
/**
run the task on the queue
*/
func run() {
if isCancelled && !isFinished { isFinished = true }
if isFinished { return }
queue.runTask(self)
}
/**
invoke the method to tell the queue if has error when the task complete
- parameter error: if the task failed, pass an error to indicate why
*/
open func complete(_ error: Error?) {
if !isExecuting {
return
}
if let error = error {
self.error = error
retries += 1
if retries >= queue.maxRetries {
cancel()
queue.log(LogLevel.trace, msg: "Task \(taskID) failed \(queue.taskList.count) tasks left")
return
}
queue.log(LogLevel.debug, msg: "Task \(taskID) retry \(retries) times")
self.run()
} else {
queue.log(LogLevel.trace, msg: "Task \(taskID) completed \(queue.taskList.count) tasks left")
isFinished = true
}
}
// MARK: - overide method
open override func start() {
super.start()
isExecuting = true
run()
}
open override func cancel() {
super.cancel()
isFinished = true
}
}
// MARK: - NSDate extention
extension Date {
init?(dateString: String) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
if let d = formatter.date(from: dateString) {
self.init(timeInterval: 0, since: d)
} else {
self.init(timeInterval: 0, since: Date())
return nil
}
}
var isoFormatter: ISOFormatter {
if let formatter = objc_getAssociatedObject(self, "formatter") as? ISOFormatter {
return formatter
} else {
let formatter = ISOFormatter()
objc_setAssociatedObject(self, "formatter", formatter, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return formatter
}
}
func toISOString() -> String {
return self.isoFormatter.string(from: self)
}
}
class ISOFormatter: DateFormatter {
override init() {
super.init()
self.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
self.timeZone = TimeZone(secondsFromGMT: 0)
self.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - Hepler
private func toJSON(_ obj: Any) throws -> String? {
let json = try JSONSerialization.data(withJSONObject: obj, options: [])
return NSString(data: json, encoding: String.Encoding.utf8.rawValue) as String?
}
private func fromJSON(_ str: String) throws -> Any? {
if let json = str.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let obj: Any = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as Any
return obj
}
return nil
}
private func runInBackgroundAfter(_ seconds: TimeInterval, callback: @escaping () -> Void) {
let delta = DispatchTime.now() + Double(Int64(seconds) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: delta, execute: callback)
}
| mit |
Spriter/SwiftyHue | Sources/Base/BridgeResourceModels/Sensors/PresenceSensor/PresenceSensor.swift | 1 | 1808 | //
// PresenceSensor.swift
// Pods
//
// Created by Jerome Schmitz on 01.05.16.
//
//
import Foundation
import Gloss
public class PresenceSensor: PartialSensor {
let config: PresenceSensorConfig
let state: PresenceSensorState
required public init?(sensor: Sensor) {
guard let sensorConfig = sensor.config else {
return nil
}
guard let sensorState = sensor.state else {
return nil
}
let config: PresenceSensorConfig = PresenceSensorConfig(sensorConfig: sensorConfig)
guard let state: PresenceSensorState = PresenceSensorState(state: sensorState) else {
return nil
}
self.config = config
self.state = state
super.init(identifier: sensor.identifier, uniqueId: sensor.uniqueId, name: sensor.name, type: sensor.type, modelId: sensor.modelId, manufacturerName: sensor.manufacturerName, swVersion: sensor.swVersion, recycle: sensor.recycle)
}
public required init?(json: JSON) {
guard let config: PresenceSensorConfig = "config" <~~ json else {
return nil
}
guard let state: PresenceSensorState = "state" <~~ json else {
return nil
}
self.config = config
self.state = state
super.init(json: json)
}
}
public func ==(lhs: PresenceSensor, rhs: PresenceSensor) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.name == rhs.name &&
lhs.state == rhs.state &&
lhs.config == rhs.config &&
lhs.type == rhs.type &&
lhs.modelId == rhs.modelId &&
lhs.manufacturerName == rhs.manufacturerName &&
lhs.swVersion == rhs.swVersion
}
| mit |
sarahlee517/Mr-Ride-iOS | Mr Ride/Mr Ride/Models/RideManager.swift | 1 | 2608 | //
// RunDataModel.swift
// Mr Ride
//
// Created by Sarah on 6/6/16.
// Copyright © 2016 AppWorks School Sarah Lee. All rights reserved.
//
import Foundation
import MapKit
import CoreData
class MyLocation: CLLocation{
let longtitude: Double = 0.0
let latitude: Double = 0.0
}
struct RideData{
var totalTime: Int = 0
var distance: Double = 0.0
var date = NSDate()
var myLocations = [MyLocation]()
}
class RideManager{
static let sharedManager = RideManager()
var distanceForChart = [Double]()
var dateForChart = [String]()
// var myCoordinate = [MyLocation]()
var historyData = [RideData]()
// var fetchResultController
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
//MARK: Get Data From Core Data
func getDataFromCoreData() {
let request = NSFetchRequest(entityName: "RideHistory")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
do {
let results = try moc.executeFetchRequest(request) as! [RideHistory]
for result in results {
// if let locations = result.locations!.array as? [Locations]{
// for locaton in locations{
// if let _longtitude = locaton.longtitude?.doubleValue,
// _latitude = locaton.latitude?.doubleValue{
//
// myCoordinate.append(
// MyLocation(
// latitude: _latitude,
// longitude: _longtitude
// )
// )
// }
// }
// }
if let distance = result.distance as? Double,
let totalTime = result.totalTime as? Int,
let date = result.date{
RideManager.sharedManager.historyData.append(
RideData(
totalTime: totalTime,
distance: distance,
date: date,
myLocations: [MyLocation]()
)
)
}
}
}catch{
fatalError("Failed to fetch data: \(error)")
}
print("History Count:\(historyData.count)")
print(historyData)
}
}
| mit |
alexzatsepin/omim | iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RouteManager/RouteManagerTableView.swift | 12 | 868 | final class RouteManagerTableView: UITableView {
@IBOutlet private weak var tableViewHeight: NSLayoutConstraint!
enum HeightUpdateStyle {
case animated
case deferred
case off
}
var heightUpdateStyle = HeightUpdateStyle.deferred
private var scheduledUpdate: DispatchWorkItem?
override var contentSize: CGSize {
didSet {
guard contentSize != oldValue else { return }
scheduledUpdate?.cancel()
let update = { [weak self] in
guard let s = self else { return }
s.tableViewHeight.constant = s.contentSize.height
}
switch heightUpdateStyle {
case .animated: superview?.animateConstraints(animations: update)
case .deferred:
scheduledUpdate = DispatchWorkItem(block: update)
DispatchQueue.main.async(execute: scheduledUpdate!)
case .off: break
}
}
}
}
| apache-2.0 |
klundberg/swift-corelibs-foundation | Foundation/NSURLSession.swift | 1 | 40609 | // 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
//
/*
NSURLSession is a replacement API for NSURLConnection. It provides
options that affect the policy of, and various aspects of the
mechanism by which NSURLRequest objects are retrieved from the
network.
An NSURLSession may be bound to a delegate object. The delegate is
invoked for certain events during the lifetime of a session, such as
server authentication or determining whether a resource to be loaded
should be converted into a download.
NSURLSession instances are threadsafe.
The default NSURLSession uses a system provided delegate and is
appropriate to use in place of existing code that uses
+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]
An NSURLSession creates NSURLSessionTask objects which represent the
action of a resource being loaded. These are analogous to
NSURLConnection objects but provide for more control and a unified
delegate model.
NSURLSessionTask objects are always created in a suspended state and
must be sent the -resume message before they will execute.
Subclasses of NSURLSessionTask are used to syntactically
differentiate between data and file downloads.
An NSURLSessionDataTask receives the resource as a series of calls to
the URLSession:dataTask:didReceiveData: delegate method. This is type of
task most commonly associated with retrieving objects for immediate parsing
by the consumer.
An NSURLSessionUploadTask differs from an NSURLSessionDataTask
in how its instance is constructed. Upload tasks are explicitly created
by referencing a file or data object to upload, or by utilizing the
-URLSession:task:needNewBodyStream: delegate message to supply an upload
body.
An NSURLSessionDownloadTask will directly write the response data to
a temporary file. When completed, the delegate is sent
URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity
to move this file to a permanent location in its sandboxed container, or to
otherwise read the file. If canceled, an NSURLSessionDownloadTask can
produce a data blob that can be used to resume a download at a later
time.
Beginning with iOS 9 and Mac OS X 10.11, NSURLSessionStream is
available as a task type. This allows for direct TCP/IP connection
to a given host and port with optional secure handshaking and
navigation of proxies. Data tasks may also be upgraded to a
NSURLSessionStream task via the HTTP Upgrade: header and appropriate
use of the pipelining option of NSURLSessionConfiguration. See RFC
2817 and RFC 6455 for information about the Upgrade: header, and
comments below on turning data tasks into stream tasks.
*/
/* DataTask objects receive the payload through zero or more delegate messages */
/* UploadTask objects receive periodic progress updates but do not return a body */
/* DownloadTask objects represent an active download to disk. They can provide resume data when canceled. */
/* StreamTask objects may be used to create NSInput and NSOutputStreams, or used directly in reading and writing. */
/*
NSURLSession is not available for i386 targets before Mac OS X 10.10.
*/
public let NSURLSessionTransferSizeUnknown: Int64 = -1
public class URLSession: NSObject {
/*
* The shared session uses the currently set global NSURLCache,
* NSHTTPCookieStorage and NSURLCredentialStorage objects.
*/
public class func sharedSession() -> URLSession { NSUnimplemented() }
/*
* Customization of NSURLSession occurs during creation of a new session.
* If you only need to use the convenience routines with custom
* configuration options it is not necessary to specify a delegate.
* If you do specify a delegate, the delegate will be retained until after
* the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
*/
public /*not inherited*/ init(configuration: URLSessionConfiguration) { NSUnimplemented() }
public /*not inherited*/ init(configuration: URLSessionConfiguration, delegate: URLSessionDelegate?, delegateQueue queue: OperationQueue?) { NSUnimplemented() }
public var delegateQueue: OperationQueue { NSUnimplemented() }
public var delegate: URLSessionDelegate? { NSUnimplemented() }
/*@NSCopying*/ public var configuration: URLSessionConfiguration { NSUnimplemented() }
/*
* The sessionDescription property is available for the developer to
* provide a descriptive label for the session.
*/
public var sessionDescription: String?
/* -finishTasksAndInvalidate returns immediately and existing tasks will be allowed
* to run to completion. New tasks may not be created. The session
* will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError:
* has been issued.
*
* -finishTasksAndInvalidate and -invalidateAndCancel do not
* have any effect on the shared session singleton.
*
* When invalidating a background session, it is not safe to create another background
* session with the same identifier until URLSession:didBecomeInvalidWithError: has
* been issued.
*/
public func finishTasksAndInvalidate() { NSUnimplemented() }
/* -invalidateAndCancel acts as -finishTasksAndInvalidate, but issues
* -cancel to all outstanding tasks for this session. Note task
* cancellation is subject to the state of the task, and some tasks may
* have already have completed at the time they are sent -cancel.
*/
public func invalidateAndCancel() { NSUnimplemented() }
public func resetWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil. */
public func flushWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* flush storage to disk and clear transient network caches. Invokes completionHandler() on the delegate queue if not nil. */
public func getTasksWithCompletionHandler(_ completionHandler: ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with outstanding data, upload and download tasks. */
public func getAllTasksWithCompletionHandler(_ completionHandler: ([URLSessionTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with all outstanding tasks. */
/*
* NSURLSessionTask objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
/* Creates a data task with the given request. The request may have a body stream. */
public func dataTaskWithRequest(_ request: URLRequest) -> URLSessionDataTask { NSUnimplemented() }
/* Creates a data task to retrieve the contents of the given URL. */
public func dataTaskWithURL(_ url: URL) -> URLSessionDataTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request will be created from the file referenced by fileURL */
public func uploadTaskWithRequest(_ request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request is provided from the bodyData. */
public func uploadTaskWithRequest(_ request: URLRequest, fromData bodyData: Data) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
public func uploadTaskWithStreamedRequest(_ request: URLRequest) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates a download task with the given request. */
public func downloadTaskWithRequest(_ request: URLRequest) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task to download the contents of the given URL. */
public func downloadTaskWithURL(_ url: URL) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
public func downloadTaskWithResumeData(_ resumeData: Data) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a bidirectional stream task to a given host and port.
*/
public func streamTaskWithHostName(_ hostname: String, port: Int) -> URLSessionStreamTask { NSUnimplemented() }
}
/*
* NSURLSession convenience routines deliver results to
* a completion handler block. These convenience routines
* are not available to NSURLSessions that are configured
* as background sessions.
*
* Task objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
extension URLSession {
/*
* data task convenience methods. These methods create tasks that
* bypass the normal delegate calls for response and data delivery,
* and provide a simple cancelable asynchronous interface to receiving
* data. Errors will be returned in the NSURLErrorDomain,
* see <Foundation/NSURLError.h>. The delegate, if any, will still be
* called for authentication challenges.
*/
public func dataTaskWithRequest(_ request: URLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionDataTask { NSUnimplemented() }
public func dataTaskWithURL(_ url: URL, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionDataTask { NSUnimplemented() }
/*
* upload convenience method.
*/
public func uploadTaskWithRequest(_ request: URLRequest, fromFile fileURL: NSURL, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionUploadTask { NSUnimplemented() }
public func uploadTaskWithRequest(_ request: URLRequest, fromData bodyData: Data?, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionUploadTask { NSUnimplemented() }
/*
* download task convenience methods. When a download successfully
* completes, the NSURL will point to a file that must be read or
* copied during the invocation of the completion routine. The file
* will be removed automatically.
*/
public func downloadTaskWithRequest(_ request: URLRequest, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithURL(_ url: NSURL, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithResumeData(_ resumeData: Data, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
}
extension URLSessionTask {
public enum State: Int {
case running /* The task is currently being serviced by the session */
case suspended
case canceling /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. */
case completed /* The task has completed and the session will receive no more delegate notifications */
}
}
/*
* NSURLSessionTask - a cancelable object that refers to the lifetime
* of processing a given request.
*/
public class URLSessionTask: NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public var taskIdentifier: Int { NSUnimplemented() } /* an identifier for this task, assigned by and unique to the owning session */
/*@NSCopying*/ public var originalRequest: URLRequest? { NSUnimplemented() } /* may be nil if this is a stream task */
/*@NSCopying*/ public var currentRequest: URLRequest? { NSUnimplemented() } /* may differ from originalRequest due to http server redirection */
/*@NSCopying*/ public var response: URLResponse? { NSUnimplemented() } /* may be nil if no response has been received */
/* Byte count properties may be zero if no body is expected,
* or NSURLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/* number of body bytes already received */
public var countOfBytesReceived: Int64 { NSUnimplemented() }
/* number of body bytes already sent */
public var countOfBytesSent: Int64 { NSUnimplemented() }
/* number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
public var countOfBytesExpectedToSend: Int64 { NSUnimplemented() }
/* number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
public var countOfBytesExpectedToReceive: Int64 { NSUnimplemented() }
/*
* The taskDescription property is available for the developer to
* provide a descriptive label for the task.
*/
public var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
public func cancel() { NSUnimplemented() }
/*
* The current state of the task within the session.
*/
public var state: State { NSUnimplemented() }
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ public var error: NSError? { NSUnimplemented() }
/*
* Suspending a task will prevent the NSURLSession from continuing to
* load data. There may still be delegate calls made on behalf of
* this task (for instance, to report data received while suspending)
* but no further transmissions will be made on behalf of the task
* until -resume is sent. The timeout timer associated with the task
* will be disabled while a task is suspended. -suspend and -resume are
* nestable.
*/
public func suspend() { NSUnimplemented() }
public func resume() { NSUnimplemented() }
/*
* Sets a scaling factor for the priority of the task. The scaling factor is a
* value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
* priority and 1.0 is considered the highest.
*
* The priority is a hint and not a hard requirement of task performance. The
* priority of a task may be changed using this API at any time, but not all
* protocols support this; in these cases, the last priority that took effect
* will be used.
*
* If no priority is specified, the task will operate with the default priority
* as defined by the constant NSURLSessionTaskPriorityDefault. Two additional
* priority levels are provided: NSURLSessionTaskPriorityLow and
* NSURLSessionTaskPriorityHigh, but use is not restricted to these.
*/
public var priority: Float
}
public let NSURLSessionTaskPriorityDefault: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityLow: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityHigh: Float = 0.0 // NSUnimplemented
/*
* An NSURLSessionDataTask does not provide any additional
* functionality over an NSURLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
public class URLSessionDataTask: URLSessionTask {
}
/*
* An NSURLSessionUploadTask does not currently provide any additional
* functionality over an NSURLSessionDataTask. All delegate messages
* that may be sent referencing an NSURLSessionDataTask equally apply
* to NSURLSessionUploadTasks.
*/
public class URLSessionUploadTask: URLSessionDataTask {
}
/*
* NSURLSessionDownloadTask is a task that represents a download to
* local storage.
*/
public class URLSessionDownloadTask: URLSessionTask {
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
public func cancelByProducingResumeData(_ completionHandler: (Data?) -> Void) { NSUnimplemented() }
}
/*
* An NSURLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via NSURLSession. This task
* may be explicitly created from an NSURLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* NSURLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create NSInputStream and NSOutputStream
* instances from an NSURLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
public class URLSessionStreamTask: URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
public func readDataOfMinLength(_ minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: (Data?, Bool, NSError?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
public func writeData(_ data: Data, timeout: TimeInterval, completionHandler: (NSError?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
public func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
public func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
public func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
public func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
public func stopSecureConnection() { NSUnimplemented() }
}
/*
* Configuration options for an NSURLSession. When a session is
* created, a copy of the configuration object is made - you cannot
* modify the configuration of a session after it has been created.
*
* The shared session uses the global singleton credential, cache
* and cookie storage objects.
*
* An ephemeral session has no persistent disk storage for cookies,
* cache or credentials.
*
* A background session can be used to perform networking operations
* on behalf of a suspended application, within certain constraints.
*/
public class URLSessionConfiguration: NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public class func defaultSessionConfiguration() -> URLSessionConfiguration { NSUnimplemented() }
public class func ephemeralSessionConfiguration() -> URLSessionConfiguration { NSUnimplemented() }
public class func backgroundSessionConfigurationWithIdentifier(_ identifier: String) -> URLSessionConfiguration { NSUnimplemented() }
/* identifier for the background session configuration */
public var identifier: String? { NSUnimplemented() }
/* default cache policy for requests */
public var requestCachePolicy: NSURLRequest.CachePolicy
/* default timeout for requests. This will cause a timeout if no data is transmitted for the given timeout value, and is reset whenever data is transmitted. */
public var timeoutIntervalForRequest: TimeInterval
/* default timeout for requests. This will cause a timeout if a resource is not able to be retrieved within a given timeout. */
public var timeoutIntervalForResource: TimeInterval
/* type of service for requests. */
public var networkServiceType: URLRequest.NetworkServiceType
/* allow request to route over cellular. */
public var allowsCellularAccess: Bool
/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
public var discretionary: Bool
/* The identifier of the shared data container into which files in background sessions should be downloaded.
* App extensions wishing to use background sessions *must* set this property to a valid container identifier, or
* all transfers in that session will fail with NSURLErrorBackgroundSessionRequiresSharedContainer.
*/
public var sharedContainerIdentifier: String?
/*
* Allows the app to be resumed or launched in the background when tasks in background sessions complete
* or when auth is required. This only applies to configurations created with +backgroundSessionConfigurationWithIdentifier:
* and the default value is YES.
*/
/* The proxy dictionary, as described by <CFNetwork/CFHTTPStream.h> */
public var connectionProxyDictionary: [NSObject : AnyObject]?
// TODO: We don't have the SSLProtocol type from Security
/*
/* The minimum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMinimumSupportedProtocol: SSLProtocol
/* The maximum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMaximumSupportedProtocol: SSLProtocol
*/
/* Allow the use of HTTP pipelining */
public var HTTPShouldUsePipelining: Bool
/* Allow the session to set cookies on requests */
public var HTTPShouldSetCookies: Bool
/* Policy for accepting cookies. This overrides the policy otherwise specified by the cookie storage. */
public var httpCookieAcceptPolicy: HTTPCookie.AcceptPolicy
/* Specifies additional headers which will be set on outgoing requests.
Note that these headers are added to the request only if not already present. */
public var HTTPAdditionalHeaders: [NSObject : AnyObject]?
/* The maximum number of simultanous persistent connections per host */
public var HTTPMaximumConnectionsPerHost: Int
/* The cookie storage object to use, or nil to indicate that no cookies should be handled */
public var httpCookieStorage: HTTPCookieStorage?
/* The credential storage object, or nil to indicate that no credential storage is to be used */
public var urlCredentialStorage: URLCredentialStorage?
/* The URL resource cache, or nil to indicate that no caching is to be performed */
public var urlCache: URLCache?
/* Enable extended background idle mode for any tcp sockets created. Enabling this mode asks the system to keep the socket open
* and delay reclaiming it when the process moves to the background (see https://developer.apple.com/library/ios/technotes/tn2277/_index.html)
*/
public var shouldUseExtendedBackgroundIdleMode: Bool
/* An optional array of Class objects which subclass NSURLProtocol.
The Class will be sent +canInitWithRequest: when determining if
an instance of the class can be used for a given URL scheme.
You should not use +[NSURLProtocol registerClass:], as that
method will register your class with the default session rather
than with an instance of NSURLSession.
Custom NSURLProtocol subclasses are not available to background
sessions.
*/
public var protocolClasses: [AnyClass]?
}
/*
* Disposition options for various delegate messages
*/
extension URLSession {
public enum AuthChallengeDisposition: Int {
case useCredential /* Use the specified credential, which may be nil */
case performDefaultHandling /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
case cancelAuthenticationChallenge /* The entire request will be canceled; the credential parameter is ignored. */
case rejectProtectionSpace /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
}
public enum ResponseDisposition: Int {
case cancel /* Cancel the load, this is the same as -[task cancel] */
case allow /* Allow the load to continue */
case becomeDownload /* Turn this request into a download */
case becomeStream /* Turn this task into a stream task */
}
}
/*
* NSURLSessionDelegate specifies the methods that a session delegate
* may respond to. There are both session specific messages (for
* example, connection based auth) as well as task based messages.
*/
/*
* Messages related to the URL session as a whole
*/
public protocol URLSessionDelegate : NSObjectProtocol {
/* The last message a session receives. A session will only become
* invalid because of a systemic error or when it has been
* explicitly invalidated, in which case the error parameter will be nil.
*/
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: NSError?)
/* If implemented, when a connection level authentication challenge
* has occurred, this delegate will be given the opportunity to
* provide authentication credentials to the underlying
* connection. Some types of authentication will apply to more than
* one request on a given connection to a server (SSL Server Trust
* challenges). If this delegate message is not implemented, the
* behavior will be to use the default handling, which may involve user
* interaction.
*/
func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
extension URLSessionDelegate {
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: NSError?) { }
func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
}
/* If an application has received an
* -application:handleEventsForBackgroundURLSession:completionHandler:
* message, the session delegate will receive this message to indicate
* that all messages previously enqueued for this session have been
* delivered. At this time it is safe to invoke the previously stored
* completion handler, or to begin any internal updates that will
* result in invoking the completion handler.
*/
/*
* Messages related to the operation of a specific task.
*/
public protocol URLSessionTaskDelegate : URLSessionDelegate {
/* An HTTP request is attempting to perform a redirection to a different
* URL. You must invoke the completion routine to allow the
* redirection, allow the redirection with a modified request, or
* pass nil to the completionHandler to cause the body of the redirection
* response to be delivered as the payload of this request. The default
* is to follow redirections.
*
* For tasks in background sessions, redirections will always be followed and this method will not be called.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void)
/* The task has received a request specific authentication challenge.
* If this delegate is not implemented, the session specific authentication challenge
* will *NOT* be called and the behavior will be the same as using the default handling
* disposition.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
/* Sent if a task requires a new, unopened body stream. This may be
* necessary when authentication has failed for any request that
* involves a body stream.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (InputStream?) -> Void)
/* Sent periodically to notify the delegate of upload progress. This
* information is also available as properties of the task.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
/* Sent as the last message related to a specific task. Error may be
* nil, which implies that no error occurred and this task is complete.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?)
}
extension URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (InputStream?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) { }
}
/*
* Messages related to the operation of a task that delivers data
* directly to the delegate.
*/
public protocol URLSessionDataDelegate : URLSessionTaskDelegate {
/* The task has received a response and no further messages will be
* received until the completion block is called. The disposition
* allows you to cancel a request or to turn a data task into a
* download task. This delegate message is optional - if you do not
* implement it, you can get the response as a property of the task.
*
* This method will not be called for background upload tasks (which cannot be converted to download tasks).
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void)
/* Notification that a data task has become a download task. No
* future messages will be sent to the data task.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeDownloadTask downloadTask: URLSessionDownloadTask)
/*
* Notification that a data task has become a bidirectional stream
* task. No future messages will be sent to the data task. The newly
* created streamTask will carry the original request and response as
* properties.
*
* For requests that were pipelined, the stream object will only allow
* reading, and the object will immediately issue a
* -URLSession:writeClosedForStream:. Pipelining can be disabled for
* all requests in a session, or by the NSURLRequest
* HTTPShouldUsePipelining property.
*
* The underlying connection is no longer considered part of the HTTP
* connection cache and won't count against the total number of
* connections per host.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeStreamTask streamTask: URLSessionStreamTask)
/* Sent when data is available for the delegate to consume. It is
* assumed that the delegate will retain and not copy the data. As
* the data may be discontiguous, you should use
* [NSData enumerateByteRangesUsingBlock:] to access it.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data)
/* Invoke the completion routine with a valid NSCachedURLResponse to
* allow the resulting data to be cached, or pass nil to prevent
* caching. Note that there is no guarantee that caching will be
* attempted for a given resource, and you should not rely on this
* message to receive the resource data.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: (CachedURLResponse?) -> Void)
}
extension URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeDownloadTask downloadTask: URLSessionDownloadTask) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: (CachedURLResponse?) -> Void) { }
}
/*
* Messages related to the operation of a task that writes data to a
* file and notifies the delegate upon completion.
*/
public protocol URLSessionDownloadDelegate : URLSessionTaskDelegate {
/* Sent when a download task that has completed a download. The delegate should
* copy or move the file at the given location to a new location as it will be
* removed when the delegate message returns. URLSession:task:didCompleteWithError: will
* still be called.
*/
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingToURL location: URL)
/* Sent periodically to notify the delegate of download progress. */
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
/* Sent when a download has been resumed. If a download failed with an
* error, the -userInfo dictionary of the error will contain an
* NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
}
extension URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { }
}
public protocol URLSessionStreamDelegate : URLSessionTaskDelegate {
/* Indiciates that the read side of a connection has been closed. Any
* outstanding reads complete, but future reads will immediately fail.
* This may be sent even when no reads are in progress. However, when
* this delegate message is received, there may still be bytes
* available. You only know that no more bytes are available when you
* are able to read until EOF. */
func urlSession(_ session: URLSession, readClosedForStreamTask streamTask: URLSessionStreamTask)
/* Indiciates that the write side of a connection has been closed.
* Any outstanding writes complete, but future writes will immediately
* fail.
*/
func urlSession(_ session: URLSession, writeClosedForStreamTask streamTask: URLSessionStreamTask)
/* A notification that the system has determined that a better route
* to the host has been detected (eg, a wi-fi interface becoming
* available.) This is a hint to the delegate that it may be
* desirable to create a new task for subsequent work. Note that
* there is no guarantee that the future task will be able to connect
* to the host, so callers should should be prepared for failure of
* reads and writes over any new interface. */
func urlSession(_ session: URLSession, betterRouteDiscoveredForStreamTask streamTask: URLSessionStreamTask)
/* The given task has been completed, and unopened NSInputStream and
* NSOutputStream objects are created from the underlying network
* connection. This will only be invoked after all enqueued IO has
* completed (including any necessary handshakes.) The streamTask
* will not receive any further delegate messages.
*/
func urlSession(_ session: URLSession, streamTask: URLSessionStreamTask, didBecomeInputStream inputStream: InputStream, outputStream: NSOutputStream)
}
extension URLSessionStreamDelegate {
func urlSession(_ session: URLSession, readClosedForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, writeClosedForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, betterRouteDiscoveredForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, streamTask: URLSessionStreamTask, didBecomeInputStream inputStream: InputStream, outputStream: NSOutputStream) { }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let NSURLSessionDownloadTaskResumeData: String = "" // NSUnimplemented
| apache-2.0 |
benlangmuir/swift | test/SILOptimizer/Inputs/pre_specialized_module2.swift | 10 | 274 | import pre_specialized_module
@frozen
public struct SomeOtherData {
public init() {}
}
@_specialize(exported: true, target: publicPrespecialized2(_:), availability: macOS 10.50, *; where T == SomeOtherData)
public func pre_specialize_publicPrespecialized<T>(_ t: T) {
}
| apache-2.0 |
eugenepavlyuk/swift-algorithm-club | GCD/GCD.playground/Contents.swift | 8 | 577 | //: Playground - noun: a place where people can play
// Recursive version
func gcd(_ a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
/*
// Iterative version
func gcd(m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
*/
func lcm(_ m: Int, _ n: Int) -> Int {
return m*n / gcd(m, n)
}
gcd(52, 39) // 13
gcd(228, 36) // 12
gcd(51357, 3819) // 57
gcd(841, 299) // 1
lcm(2, 3) // 6
lcm(10, 8) // 40
| mit |
rabbitinspace/Sweetend | Sources/App/Server/Endpoint.swift | 1 | 229 | import Vapor
enum Endpoint: String {
case auth
}
extension Droplet {
func resource<Resource: ResourceRepresentable>(_ endpoint: Endpoint, resource: Resource) {
self.resource(endpoint.rawValue, resource)
}
}
| mit |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/Chula Expo 2017/FacultyDescCell.swift | 1 | 1390 | //
// FacultyDescCell.swift
// Chula Expo 2017
//
// Created by NOT on 2/26/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
class FacultyDescCell: UITableViewCell {
var facityTitle: String? {
didSet{
updateUI()
}
}
var facityDesc: String? {
didSet{
updateUI()
}
}
var facTag: String?{
didSet{
if let tag = facTag{
tagCap.setText(name: tag)
}
else{
tagCap.text = nil
}
}
}
@IBOutlet var titleLabel: UILabel!
@IBOutlet var descLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBOutlet var tagCap: CapsuleUILabel!
private func updateUI(){
titleLabel.text = nil
descLabel.text = nil
if let title = facityTitle {
titleLabel.text = title
}
if let desc = facityDesc {
descLabel.text = desc
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
tottakai/RxSwift | RxCocoa/macOS/NSTextField+Rx.swift | 8 | 3223 | //
// NSTextField+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(macOS)
import Foundation
import Cocoa
#if !RX_NO_MODULE
import RxSwift
#endif
/// Delegate proxy for `NSTextField`.
///
/// For more information take a look at `DelegateProxyType`.
public class RxTextFieldDelegateProxy
: DelegateProxy
, NSTextFieldDelegate
, DelegateProxyType {
fileprivate let textSubject = PublishSubject<String?>()
/// Typed parent object.
public weak private(set) var textField: NSTextField?
/// Initializes `RxTextFieldDelegateProxy`
///
/// - parameter parentObject: Parent object for delegate proxy.
public required init(parentObject: AnyObject) {
self.textField = (parentObject as! NSTextField)
super.init(parentObject: parentObject)
}
// MARK: Delegate methods
public override func controlTextDidChange(_ notification: Notification) {
let textField = notification.object as! NSTextField
let nextValue = textField.stringValue
self.textSubject.on(.next(nextValue))
}
// MARK: Delegate proxy methods
/// For more information take a look at `DelegateProxyType`.
public override class func createProxyForObject(_ object: AnyObject) -> AnyObject {
let control = (object as! NSTextField)
return castOrFatalError(control.createRxDelegateProxy())
}
/// For more information take a look at `DelegateProxyType`.
public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let textField: NSTextField = castOrFatalError(object)
return textField.delegate
}
/// For more information take a look at `DelegateProxyType`.
public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let textField: NSTextField = castOrFatalError(object)
textField.delegate = castOptionalOrFatalError(delegate)
}
}
extension NSTextField {
/// Factory method that enables subclasses to implement their own `delegate`.
///
/// - returns: Instance of delegate proxy that wraps `delegate`.
public func createRxDelegateProxy() -> RxTextFieldDelegateProxy {
return RxTextFieldDelegateProxy(parentObject: self)
}
}
extension Reactive where Base: NSTextField {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy {
return RxTextFieldDelegateProxy.proxyForObject(base)
}
/// Reactive wrapper for `text` property.
public var text: ControlProperty<String?> {
let delegate = RxTextFieldDelegateProxy.proxyForObject(base)
let source = Observable.deferred { [weak textField = self.base] in
delegate.textSubject.startWith(textField?.stringValue)
}.takeUntil(deallocated)
let observer = UIBindingObserver(UIElement: base) { (control, value: String?) in
control.stringValue = value ?? ""
}
return ControlProperty(values: source, valueSink: observer.asObserver())
}
}
#endif
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/Collapsable Header/CollapsableHeaderView.swift | 2 | 420 | import UIKit
class CollapsableHeaderView: UIView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard let result = super.hitTest(point, with: event),
result.isUserInteractionEnabled,
result != self // Ignore touches for self but accept them for the accessory view
else {
return nil
}
return result
}
}
| gpl-2.0 |
royhsu/tiny-core | Sources/Core/Auth/Basic+HTTPHeaderRepresentable.swift | 1 | 522 | //
// Basic+HTTPHeaderRepresentable.swift
// TinyCore
//
// Created by Roy Hsu on 2019/3/16.
// Copyright © 2019 TinyWorld. All rights reserved.
//
// MARK: - HTTPHeaderRepresentable
extension Basic: HTTPHeaderRepresentable {
public func httpHeader() throws -> (field: HTTPHeader, value: String) {
let data = Data("\(username):\(password)".utf8)
let credentials = data.base64EncodedString()
return (
.authorization,
"Basic \(credentials)"
)
}
}
| mit |
thewisecity/declarehome-ios | CookedApp/TableViewControllers/GroupsCheckboxTableViewController.swift | 1 | 3960 | //
// GroupsCheckboxTableViewController.swift
// CookedApp
//
// Created by Dexter Lohnes on 11/2/15.
// Copyright © 2015 The Wise City. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class GroupsCheckboxTableViewController: PFQueryTableViewController, GroupCheckboxDelegate {
var delegate: GroupCheckboxTableViewDelegate?
var selectedGroups: NSMutableArray
required init?(coder aDecoder: NSCoder) {
selectedGroups = NSMutableArray()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 54.0
self.title = "Select Groups for Alert"
}
func addNavBarDoneButton() -> Void
{
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "finishGroupSelection"), animated: true)
}
func finishGroupSelection() -> Void
{
delegate?.finishedChoosingGroups(selectedGroups as AnyObject as! [Group])
print("Finished")
}
func removeNavBarDoneButton() -> Void
{
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func queryForTable() -> PFQuery
{
let query = PFQuery(className: self.parseClassName!)
query.orderByAscending("city")
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell?
{
let cellIdentifier = "GroupCheckboxCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? GroupCheckboxCell
if cell == nil {
cell = GroupCheckboxCell(style: .Subtitle, reuseIdentifier: cellIdentifier)
}
// We don't want these cells to light up when we touch them
cell?.selectionStyle = .None
// Configure the cell to show todo item with a priority at the bottom
if let group = object as? Group {
cell?.group = group
}
cell?.delegate = self
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let cell:GroupCheckboxCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) as! GroupCheckboxCell
// cell.checkSwitch.removeFromSuperview()
// cell.checkSwitch.setOn(true, animated: true)
// cell.checkSwitch.setNeedsDisplay()
//
// let selectedGroup = objectAtIndexPath(indexPath) as? Group
// performSegueWithIdentifier("ViewMessageWallSegue", sender: selectedGroup)
}
// 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.
if let selectedGroup = sender as? Group{
if let destinationController = segue.destinationViewController as? MessageWallViewController {
destinationController.group = selectedGroup
}
}
}
// Delegate methods
func groupCheckChanged(cell: GroupCheckboxCell, isChecked: Bool) -> Void
{
if(isChecked == true)
{
selectedGroups.addObject(cell.group)
}
else
{
selectedGroups.removeObject(cell.group)
}
if(selectedGroups.count > 0)
{
addNavBarDoneButton()
}
else
{
removeNavBarDoneButton()
}
}
}
| gpl-3.0 |
andreamazz/Tropos | Sources/Tropos/ViewControllers/TextViewController.swift | 3 | 764 | import UIKit
class TextViewController: UIViewController {
@IBOutlet var textView: UITextView!
@objc var text: String?
override func viewDidLoad() {
super.viewDidLoad()
textView.contentInset = UIEdgeInsets.zero
textView.textContainerInset = UIEdgeInsets(
top: 20.0,
left: 20.0,
bottom: 20.0,
right: 20.0
)
textView.font = UIFont.defaultRegularFont(size: 14)
textView.textColor = .lightText
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.text = text
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textView.contentOffset = .zero
}
}
| mit |
nsagora/validation-toolkit | Sources/Predicates/Standard/BlockPredicate.swift | 1 | 1971 | import Foundation
/**
The `BlockPredicate` struct defines a closure based condition used to evaluate generic inputs.
```swift
let predicate = BlockPredicate<Int> {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
*/
public struct BlockPredicate<T>: Predicate {
public typealias InputType = T
private let evaluationBlock: (InputType) -> Bool
/**
Returns a new `BlockPredicate` instance.
```swift
let predicate = BlockPredicate<Int> {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter input: The input against which to evaluate the receiver.
*/
public init(evaluationBlock: @escaping (_ input: InputType) -> Bool) {
self.evaluationBlock = evaluationBlock
}
/**
Returns a `Boolean` value that indicates whether a given input matches the evaluation closure specified by the receiver.
- parameter input: The input against which to evaluate the receiver.
- returns: `true` if input matches the validation closure specified by the receiver, otherwise `false`.
*/
public func evaluate(with input: InputType) -> Bool {
return evaluationBlock(input)
}
}
// MARK: - Dynamic Lookup Extension
extension Predicate {
/**
Returns a new `BlockPredicate` instance.
```swift
let predicate: BlockPredicate<Int> = .block {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter input: The input against which to evaluate the receiver.
*/
public static func block<T>(evaluationBlock: @escaping (_ input: T) -> Bool) -> Self where Self == BlockPredicate<T> {
BlockPredicate(evaluationBlock: evaluationBlock)
}
}
| mit |
Mindera/Alicerce | Tests/AlicerceTests/View/CollectionViewCellTestCase.swift | 1 | 1506 | import XCTest
@testable import Alicerce
final class MockCollectionViewCell: CollectionViewCell {
private(set) var setUpSubviewsCallCount = 0
private(set) var setUpConstraintsCallCount = 0
override func setUpSubviews() {
super.setUpSubviews()
setUpSubviewsCallCount += 1
}
override func setUpConstraints() {
super.setUpConstraints()
setUpConstraintsCallCount += 1
}
}
class CollectionViewCellTestCase: XCTestCase {
func testInit_WithFrame_ShouldCreateInstance() {
let _ = CollectionViewCell(frame: .zero)
}
func testInit_WithCoder_ShouldCreateInstance() {
guard let _: CollectionViewCell = UIView.instantiateFromNib(withOwner: self,
bundle: Bundle(for: TestDummy.self))
else {
return XCTFail("failed to load view from nib!")
}
}
func testInit_WithFrame_ShouldInvokeSetUpMethods() {
let cell = MockCollectionViewCell(frame: .zero)
XCTAssertEqual(cell.setUpSubviewsCallCount, 1)
XCTAssertEqual(cell.setUpConstraintsCallCount, 1)
}
func testInit_WithCoder_ShouldInvokeSetUpMethods() {
guard let cell: MockCollectionViewCell = UIView.instantiateFromNib(withOwner: self) else {
return XCTFail("failed to load view from nib!")
}
XCTAssertEqual(cell.setUpSubviewsCallCount, 1)
XCTAssertEqual(cell.setUpConstraintsCallCount, 1)
}
}
| mit |
otanistudio/NaiveHTTP | NaiveHTTPTests/UtilityTests.swift | 1 | 1331 | //
// NormalizedURLTests.swift
// NaiveHTTP
//
// Created by Robert Otani on 9/6/15.
// Copyright © 2015 otanistudio.com. All rights reserved.
//
import XCTest
import NaiveHTTP
class UtilityTests: XCTestCase {
func testNormalizedURLInit() {
let testQueryParams = ["a":"123","b":"456"]
let url = URL(string: "http://example.com", params: testQueryParams)
XCTAssertEqual(URL(string: "http://example.com?a=123&b=456"), url)
}
func testNormalizedURLWithExistingQueryParameters() {
let testQueryParams = ["a":"123","b":"456"]
let url = URL(string: "http://example.com?c=xxx&d=yyy", params: testQueryParams)
XCTAssertEqual(URL(string: "http://example.com?a=123&b=456&c=xxx&d=yyy"), url)
}
func testNormalizedURLWithNilQueryParam() {
let url = URL(string: "http://example.com", params: nil)
let expectedURL = URL(string: "http://example.com")
XCTAssertEqual(expectedURL, url)
}
// func testFilteredJSON() {
// let str: String = "while(1);\n[\"bleh\", \"blah\"]"
// let data: Data = str.data(using: String.Encoding.utf8)!
// let json = SwiftyHTTP.filteredJSON("while(1);", data: data)
// let expected: JSON = ["bleh", "blah"]
// XCTAssertEqual(expected, json)
// }
}
| mit |
PiXeL16/BudgetShare | BudgetShareTests/Modules/Login/View/MockLoginView.swift | 1 | 787 | //
// MockLoginView.swift
// BudgetShareTests
//
// Created by Chris Jimenez on 9/17/17.
// Copyright © 2017 Chris Jimenez. All rights reserved.
//
@testable import BudgetShare
import Foundation
import UIKit
class MockLoginView: LoginView {
var controller: UIViewController?
var presenter: LoginModule!
var didTapLoginCalled = false
var didTapSignUpCalled = false
var didReceiveErrorCalled = false
var loginSuccesfullCalled = false
func didTapLogin() {
didTapLoginCalled = true
}
func didTapSignUp() {
didTapSignUpCalled = true
}
func didReceiveError(message: String) {
didReceiveErrorCalled = true
}
func loginSuccesful() {
loginSuccesfullCalled = true
}
}
| mit |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Factories/ViewControllerFactory.swift | 2 | 18650 | //
// ViewControllerFactory.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 06/09/16.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class ViewControllerFactory: ViewControllerFactoryProtocol {
// MARK: ViewControllerFactoryProtocol
required init(managerFactory: ManagerFactoryProtocol) {
_managerFactory = managerFactory
}
// MARK: Intro
func launchViewController(context: Any?)->LaunchViewController {
let vc = viewControllerFromXib(classType: LaunchViewController.self, context: context) as! LaunchViewController
vc.model = self.model(classType: LaunchModel.self as AnyClass, context: context) as? LaunchModel
return vc
}
func walkthroughViewController(context: Any?)->WalkthroughViewController {
let vc = viewControllerFromXib(classType: WalkthroughViewController.self, context: context) as! WalkthroughViewController
vc.model = self.model(classType: WalkthroughModel.self as AnyClass, context: context) as? WalkthroughModel
return vc
}
// MARK: Content
func homeViewController(context: Any?)->HomeViewController {
let vc = viewControllerFromSb(classType: HomeViewController.self, context: context) as! HomeViewController
vc.model = self.model(classType: HomeModel.self as AnyClass, context: context) as? HomeModel
return vc
}
func photoDetailsViewController(context: Any?)->PhotoDetailsViewController {
let vc = viewControllerFromSb(classType: PhotoDetailsViewController.self, context: context) as! PhotoDetailsViewController
vc.model = self.model(classType: PhotoDetailsModel.self as AnyClass, context: context) as? PhotoDetailsModel
return vc
}
// MARK: User
func startViewController(context: Any?)->StartViewController {
let vc = viewControllerFromSb(classType: StartViewController.self, context: context) as! StartViewController
vc.model = self.model(classType: StartModel.self as AnyClass, context: context) as? StartModel
return vc
}
func userContainerViewController(context: Any?)->UserContainerViewController {
let vc = viewControllerFromSb(classType: UserContainerViewController.self, context: context) as! UserContainerViewController
vc.model = self.model(classType: UserContainerModel.self as AnyClass, context: context) as? UserContainerModel
vc.startVC = self.startViewController(context: nil)
vc.startVC?.delegate = vc
vc.loginVc = self.userLoginViewController(context: nil)
vc.loginVc?.delegate = vc
return vc
}
func userLoginViewController(context: Any?)->UserLoginViewController {
let vc = viewControllerFromSb(classType: UserLoginViewController.self, context: context) as! UserLoginViewController
vc.model = self.model(classType: UserLoginModel.self as AnyClass, context: context) as? UserLoginModel
return vc
}
func userSignUpViewController(context: Any?)->UserSignUpViewController {
let vc = viewControllerFromSb(classType: UserSignUpViewController.self, context: context) as! UserSignUpViewController
vc.model = self.model(classType: SignUpModel.self as AnyClass, context: context) as? SignUpModel
return vc
}
func userResetPasswordViewController(context: Any?)->UserResetPasswordViewController {
let vc = viewControllerFromSb(classType: UserResetPasswordViewController.self, context: context) as! UserResetPasswordViewController
vc.model = self.model(classType: UserResetPasswordModel.self as AnyClass, context: context) as? UserResetPasswordModel
return vc
}
func userProfileViewController(context: Any?)->UserProfileViewController {
let vc = viewControllerFromSb(classType: UserProfileViewController.self, context: context) as! UserProfileViewController
vc.model = self.model(classType: UserProfileModel.self as AnyClass, context: context) as? UserProfileModel
return vc
}
// Legal
func termsConditionsViewController(context: Any?)->TermsConditionsViewController {
let vc = viewControllerFromSb(classType: TermsConditionsViewController.self, context: context) as! TermsConditionsViewController
vc.model = self.model(classType: TermsConditionsModel.self as AnyClass, context: context) as? TermsConditionsModel
return vc
}
func privacyPolicyViewController(context: Any?)->PrivacyPolicyViewController {
let vc = viewControllerFromSb(classType: PrivacyPolicyViewController.self, context: context) as! PrivacyPolicyViewController
vc.model = self.model(classType: PrivacyPolicyModel.self as AnyClass, context: context) as? PrivacyPolicyModel
return vc
}
// MARK: Maps
func mapsViewController(context: Any?)->MapsViewController {
let vc = viewControllerFromSb(classType: MapsViewController.self, context: context) as! MapsViewController
vc.model = self.model(classType: MapsModel.self as AnyClass, context: context) as? MapsModel
return vc
}
// MARK: Menu
func menuViewController(context: Any?)->MenuViewController {
let vc = viewControllerFromSb(classType: MenuViewController.self, context: context) as! MenuViewController
vc.model = self.model(classType: MenuModel.self as AnyClass, context: context) as? MenuModel
vc.model?.viewControllerFactory = self
return vc
}
// MARK: Reusable
func countryPickerViewController(context: Any?)->CountryPickerViewController {
let vc = viewControllerFromSb(classType: CountryPickerViewController.self, context: context) as! CountryPickerViewController
vc.model = self.model(classType: CountryPickerModel.self as AnyClass, context: context) as? CountryPickerModel
return vc
}
func contactViewController(context: Any?)->ContactViewController {
let vc = viewControllerFromSb(classType: ContactViewController.self, context: context) as! ContactViewController
vc.model = self.model(classType: ContactModel.self as AnyClass, context: context) as? ContactModel
return vc
}
func settingsViewController(context: Any?)->SettingsViewController {
let vc = viewControllerFromSb(classType: SettingsViewController.self, context: context) as! SettingsViewController
vc.model = self.model(classType: SettingsModel.self as AnyClass, context: context) as? SettingsModel
return vc
}
// MARK: Demo
func tableViewExampleViewController(context: Any?)->TableViewExampleViewController {
let vc = viewControllerFromSb(classType: TableViewExampleViewController.self, context: context) as! TableViewExampleViewController
vc.model = self.model(classType: TableViewExampleModel.self as AnyClass, context: context) as? TableViewExampleModel
return vc
}
func tableWithSearchViewController(context: Any?)->TableWithSearchViewController {
let vc = viewControllerFromSb(classType: TableWithSearchViewController.self, context: context) as! TableWithSearchViewController
vc.model = self.model(classType: TableWithSearchModel.self as AnyClass, context: context) as? TableWithSearchModel
return vc
}
// MARK:
// MARK: Internal
// MARK:
internal var _managerFactory: ManagerFactoryProtocol
// Returns true if viewController had property and it was injected with the value
// The approach used from: https://thatthinginswift.com/dependency-injection-storyboards-swift/
// Using Mirror for reflection and KVO for injecting
internal func needsDependency(viewController: UIViewController, propertyName: String)->Bool {
var result: Bool = false
let vcMirror = Mirror(reflecting: viewController)
let superVcMirror: Mirror? = vcMirror.superclassMirror
let superSuperVcMirror: Mirror? = superVcMirror?.superclassMirror
let superSuperSuperVcMirror: Mirror? = superSuperVcMirror?.superclassMirror
result = self.containsProperty(mirror: vcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superVcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superSuperVcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superSuperSuperVcMirror, propertyName: propertyName)
return result
}
internal func containsProperty(mirror: Mirror?, propertyName: String) -> Bool {
var result: Bool = false
if let mirror = mirror {
let vcProperties = mirror.children.filter { ($0.label ?? "").isEqual(propertyName) }
if vcProperties.first != nil {
result = true
}
}
return result
}
internal func name(viewControllerClassType: AnyClass)->String {
var viewControllerClassName: String = NSStringFromClass(viewControllerClassType)
// Autopick depending on platform
if isIpad {
viewControllerClassName = viewControllerClassName + "_ipad"
} else if isIphone {
viewControllerClassName = viewControllerClassName + "_iphone"
}
return viewControllerClassName
}
internal func viewControllerFromSb(classType: AnyClass, context: Any?)->UIViewController {
var viewControllerClassName: String = self.name(viewControllerClassType: classType)
viewControllerClassName = viewControllerClassName.components(separatedBy: ".").last!
let storyboard = UIStoryboard(name: viewControllerClassName, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: viewControllerClassName)
injectDependencies(viewController: vc, context: context)
return vc
}
internal func viewControllerFromXib(classType: AnyClass, context: Any?)->UIViewController {
let viewControllerClassName: String = self.name(viewControllerClassType: classType)
//let deviceClass: AnyClass? = NSClassFromString(viewControllerClassName);
let deviceClass = NSClassFromString(viewControllerClassName) as! UIViewController.Type
let vc: UIViewController = deviceClass.init()
injectDependencies(viewController: vc, context: context)
return vc
}
/*override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var vc = segue.destination as! GenericViewControllerProtocol;
self.injectDependencies(viewController: &vc);
//if (segue.identifier == "Load View") {
// pass data to next view
//}
}*/
func injectDependencies(viewController: UIViewController, context: Any?) {
if self.needsDependency(viewController: viewController, propertyName: "context") {
(viewController as! GenericViewControllerProtocol).context = context
}
if self.needsDependency(viewController: viewController, propertyName: "viewLoader") {
(viewController as! GenericViewControllerProtocol).viewLoader = self.viewLoader()
}
if self.needsDependency(viewController: viewController, propertyName: "crashManager") {
(viewController as! GenericViewControllerProtocol).crashManager = self._managerFactory.crashManager
}
if self.needsDependency(viewController: viewController, propertyName: "analyticsManager") {
(viewController as! GenericViewControllerProtocol).analyticsManager = self._managerFactory.analyticsManager
}
if self.needsDependency(viewController: viewController, propertyName: "messageBarManager") {
(viewController as! GenericViewControllerProtocol).messageBarManager = self._managerFactory.messageBarManager
}
if self.needsDependency(viewController: viewController, propertyName: "viewControllerFactory") {
(viewController as! GenericViewControllerProtocol).viewControllerFactory = self
}
if self.needsDependency(viewController: viewController, propertyName: "localizationManager") {
(viewController as! GenericViewControllerProtocol).localizationManager = self._managerFactory.localizationManager
}
if self.needsDependency(viewController: viewController, propertyName: "userManager") {
(viewController as! GenericViewControllerProtocol).userManager = self._managerFactory.userManager
}
if self.needsDependency(viewController: viewController, propertyName: "reachabilityManager") {
(viewController as! GenericViewControllerProtocol).reachabilityManager = self._managerFactory.reachabilityManager
self.addNetworkStatusObserving(viewController: viewController as! GenericViewControllerProtocol)
}
}
func addNetworkStatusObserving(viewController: GenericViewControllerProtocol) {
weak var weakGenericViewController = viewController
weak var weakViewController = (viewController as! UIViewController)
// TODO: not calling after second on/off switch
self._managerFactory.reachabilityManager.addServiceObserver(observer: weakViewController as! ReachabilityManagerObserver, notificationType: ReachabilityManagerNotificationType.internetDidBecomeOn, callback: { /*[weak self]*/ (success, result, context, error) in
let lastVc = weakViewController?.navigationController?.viewControllers.last
// Check for error and only handle once, inside last screen
if (lastVc == weakViewController) {
weakGenericViewController?.viewLoader?.hideNoInternetConnectionLabel(containerView: (weakViewController?.view)!)
}
}, context: nil)
self._managerFactory.reachabilityManager.addServiceObserver(observer: weakViewController as! ReachabilityManagerObserver
, notificationType: ReachabilityManagerNotificationType.internetDidBecomeOff, callback: { /*[weak self]*/ (success, result, context, error) in
weakGenericViewController?.viewLoader?.showNoInternetConnectionLabel(containerView: (weakViewController?.view)!)
}, context: nil)
// Subscribe and handle network errors
let notificationCenter: NotificationCenter = NotificationCenter.default
notificationCenter.addObserver(forName: NetworkRequestError.notification, object: self, queue: nil) { [weak self] (notification) in
if let info = notification.userInfo as? Dictionary<String,Error> {
let error: ErrorEntity? = info[NetworkRequestError.notificationUserInfoErrorKey] as? ErrorEntity
if let error = error {
// Check for error and only handle once, inside last screen
if (weakViewController?.navigationController?.viewControllers.last == weakViewController) {
if (error.code == NetworkRequestError.unauthorized.code) {
// Go to start
weakGenericViewController?.logoutAndGoBackToAppStart(error: error)
} else {
self?._managerFactory.messageBarManager.showMessage(title: " ", description: error.message, type: MessageBarMessageType.error)
}
}
}
}
}
}
internal func model(classType: AnyClass, context: Any?) -> BaseModel {
let className: String = NSStringFromClass(classType)
let deviceClass = NSClassFromString(className) as! BaseModel.Type
let model: BaseModel = deviceClass.init()
model.userManager = _managerFactory.userManager
model.settingsManager = _managerFactory.settingsManager
model.networkOperationFactory = _managerFactory.networkOperationFactory
model.reachabilityManager = _managerFactory.reachabilityManager
model.analyticsManager = _managerFactory.analyticsManager
model.context = context
model.commonInit()
return model
}
internal func viewLoader()->ViewLoader {
let loader: ViewLoader = ViewLoader()
return loader
}
}
| mit |
practicalswift/swift | validation-test/compiler_crashers_fixed/01283-swift-modulefile-getdecl.swift | 65 | 619 | // 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: not %target-swift-frontend %s -typecheck
class e {
var _ = d() {
class A {
class func a() -> Self {
}
}
func b<T>(t: AnyObject.Type) -> T! {
}
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
}
protocol e {
}
protocol i : d { func d
| apache-2.0 |
tbaranes/SwiftyUtils | Sources/Extensions/UIKit/UIStoryboard/UIStoryboardExtension.swift | 1 | 518 | //
// Created by Tom Baranes on 23/06/16.
// Copyright © 2016 Tom Baranes. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
extension UIStoryboard {
/// Get the main application storyboard.
public class var main: UIStoryboard? {
let bundle = Bundle.main
guard let storyboardName = bundle.object(forInfoDictionaryKey: "UIMainStoryboardFile") as? String else {
return nil
}
return UIStoryboard(name: storyboardName, bundle: bundle)
}
}
#endif
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14021-swift-sourcemanager-getmessage.swift | 11 | 251 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for b let {
enum S {
let a {
class
b {
struct g { func i( ) -> ( ) {
class
case ,
| mit |
zhuozhuo/ZHChat | SwiftExample/ZHChatSwift/ZHRootTableViewController.swift | 1 | 2367 | //
// ZHRootTableViewController.swift
// ZHChatSwift
//
// Created by aimoke on 16/12/15.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
class ZHRootTableViewController: UITableViewController {
var dataArray: [String] = ["Push","Present"];
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView.init();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RootreuseIdentifier", for: indexPath);
cell.textLabel?.text = dataArray[indexPath.row];
// Configure the cell...
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row);
switch indexPath.row {
case 0:
let messagesVC: ZHCDemoMessagesViewController = ZHCDemoMessagesViewController.init();
messagesVC.presentBool = false;
self.navigationController?.pushViewController(messagesVC, animated: true);
case 1:
let messagesVC: ZHCDemoMessagesViewController = ZHCDemoMessagesViewController.init();
messagesVC.presentBool = true;
let nav: UINavigationController = UINavigationController.init(rootViewController: messagesVC);
self.navigationController?.present(nav, animated: true, completion: nil);
default:
break;
}
}
/*
// 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.
}
*/
}
| mit |
smoope/swift-client-conversation | Framework/Source/LoadingSupplementaryView.swift | 1 | 1385 | //
// Copyright 2017 smoope GmbH
//
// 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
internal class LoadingSupplementaryView: UICollectionReusableView {
internal var activityIndicatorView: UIActivityIndicatorView
override init(frame: CGRect) {
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
super.init(frame: frame)
addSubview(activityIndicatorView)
centerXAnchor.constraint(equalTo: activityIndicatorView.centerXAnchor).isActive = true
centerYAnchor.constraint(equalTo: activityIndicatorView.centerYAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
toco/IPDC-14 | IPDC/AppDelegate.swift | 1 | 2238 | //
// AppDelegate.swift
// IPDC
//
// Created by Tobias Conradi on 03.11.14.
// Copyright (c) 2014 Tobias Conradi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if let splitViewController = window?.rootViewController as? UISplitViewController {
splitViewController.preferredDisplayMode = .AllVisible
}
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 throttle down OpenGL ES frame rates. 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 inactive 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 |
mightydeveloper/swift | stdlib/public/core/Policy.swift | 9 | 15662 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The empty tuple type.
///
/// This is the default return type of functions for which no explicit
/// return type is specified.
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
// Integer literals are limited to 2048 bits.
// The intent is to have arbitrary-precision literals, but implementing that
// requires more work.
//
// Rationale: 1024 bits are enough to represent the absolute value of min/max
// IEEE Binary64, and we need 1 bit to represent the sign. Instead of using
// 1025, we use the next round number -- 2048.
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
#if arch(i386) || arch(x86_64)
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
/// The protocol to which all types implicitly conform.
public typealias Any = protocol<>
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// When used as a concrete type, all known `@objc` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyObject`. For
/// example:
///
/// class C {
/// @objc func getCValue() -> Int { return 42 }
/// }
///
/// // If x has a method @objc getValue()->Int, call it and
/// // return the result. Otherwise, return nil.
/// func getCValue1(x: AnyObject) -> Int? {
/// if let f: ()->Int = x.getCValue { // <===
/// return f()
/// }
/// return nil
/// }
///
/// // A more idiomatic implementation using "optional chaining"
/// func getCValue2(x: AnyObject) -> Int? {
/// return x.getCValue?() // <===
/// }
///
/// // An implementation that assumes the required method is present
/// func getCValue3(x: AnyObject) -> Int { // <===
/// return x.getCValue() // x.getCValue is implicitly unwrapped. // <===
/// }
///
/// - SeeAlso: `AnyClass`
@objc
public protocol AnyObject : class {}
#else
/// The protocol to which all classes implicitly conform.
///
/// - SeeAlso: `AnyClass`
public protocol AnyObject : class {}
#endif
// Implementation note: the `AnyObject` protocol *must* not have any method or
// property requirements.
// FIXME: AnyObject should have an alternate version for non-objc without
// the @objc attribute, but AnyObject needs to be not be an address-only
// type to be able to be the target of castToNativeObject and an empty
// non-objc protocol appears not to be. There needs to be another way to make
// this the right kind of object.
/// The protocol to which all class types implicitly conform.
///
/// When used as a concrete type, all known `@objc` `class` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyClass`. For
/// example:
///
/// class C {
/// @objc class var cValue: Int { return 42 }
/// }
///
/// // If x has an @objc cValue: Int, return its value.
/// // Otherwise, return nil.
/// func getCValue(x: AnyClass) -> Int? {
/// return x.cValue // <===
/// }
///
/// - SeeAlso: `AnyObject`
public typealias AnyClass = AnyObject.Type
@warn_unused_result
public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return Bool(Builtin.cmp_eq_RawPointer(
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(l)),
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(r))
))
case (nil, nil):
return true
default:
return false
}
}
@warn_unused_result
public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
return !(lhs === rhs)
}
//
// Equatable
//
/// Instances of conforming types can be compared for value equality
/// using operators `==` and `!=`.
///
/// When adopting `Equatable`, only the `==` operator is required to be
/// implemented. The standard library provides an implementation for `!=`.
public protocol Equatable {
/// Return true if `lhs` is equal to `rhs`.
///
/// **Equality implies substitutability**. When `x == y`, `x` and
/// `y` are interchangeable in any code that only depends on their
/// values.
///
/// Class instance identity as distinguished by triple-equals `===`
/// is notably not part of an instance's value. Exposing other
/// non-value aspects of `Equatable` types is discouraged, and any
/// that *are* exposed should be explicitly pointed out in
/// documentation.
///
/// **Equality is an equivalence relation**
///
/// - `x == x` is `true`
/// - `x == y` implies `y == x`
/// - `x == y` and `y == z` implies `x == z`
///
/// **Inequality is the inverse of equality**, i.e. `!(x == y)` iff
/// `x != y`.
@warn_unused_result
func == (lhs: Self, rhs: Self) -> Bool
}
@warn_unused_result
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool {
return !(lhs == rhs)
}
//
// Comparable
//
@warn_unused_result
public func > <T : Comparable>(lhs: T, rhs: T) -> Bool {
return rhs < lhs
}
@warn_unused_result
public func <= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(rhs < lhs)
}
@warn_unused_result
public func >= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(lhs < rhs)
}
/// Instances of conforming types can be compared using relational
/// operators, which define a [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order).
///
/// A type conforming to `Comparable` need only supply the `<` and
/// `==` operators; default implementations of `<=`, `>`, `>=`, and
/// `!=` are supplied by the standard library:
///
/// struct Singular : Comparable {}
/// func ==(x: Singular, y: Singular) -> Bool { return true }
/// func <(x: Singular, y: Singular) -> Bool { return false }
///
/// **Axioms**, in addition to those of `Equatable`:
///
/// - `x == y` implies `x <= y`, `x >= y`, `!(x < y)`, and `!(x > y)`
/// - `x < y` implies `x <= y` and `y > x`
/// - `x > y` implies `x >= y` and `y < x`
/// - `x <= y` implies `y >= x`
/// - `x >= y` implies `y <= x`
public protocol Comparable : Equatable {
/// A [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order)
/// over instances of `Self`.
@warn_unused_result
func < (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func <= (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func >= (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func > (lhs: Self, rhs: Self) -> Bool
}
/// A set type with O(1) standard bitwise operators.
///
/// Each instance is a subset of `~Self.allZeros`.
///
/// **Axioms**, where `x` is an instance of `Self`:
///
/// - `x | Self.allZeros == x`
/// - `x ^ Self.allZeros == x`
/// - `x & Self.allZeros == .allZeros`
/// - `x & ~Self.allZeros == x`
/// - `~x == x ^ ~Self.allZeros`
public protocol BitwiseOperationsType {
/// Returns the intersection of bits set in `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func & (lhs: Self, rhs: Self) -> Self
/// Returns the union of bits set in `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func | (lhs: Self, rhs: Self) -> Self
/// Returns the bits that are set in exactly one of `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func ^ (lhs: Self, rhs: Self) -> Self
/// Returns `x ^ ~Self.allZeros`.
///
/// - Complexity: O(1).
@warn_unused_result
prefix func ~ (x: Self) -> Self
/// The empty bitset.
///
/// Also the [identity element](http://en.wikipedia.org/wiki/Identity_element) for `|` and
/// `^`, and the [fixed point](http://en.wikipedia.org/wiki/Fixed_point_(mathematics)) for
/// `&`.
static var allZeros: Self { get }
}
@warn_unused_result
public func |= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs | rhs
}
@warn_unused_result
public func &= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs & rhs
}
@warn_unused_result
public func ^= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs ^ rhs
}
/// Instances of conforming types provide an integer `hashValue` and
/// can be used as `Dictionary` keys.
public protocol Hashable : Equatable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
var hashValue: Int { get }
}
public protocol _SinkType {}
@available(*, unavailable, message="SinkType has been removed. Use (T)->() closures directly instead.")
public typealias SinkType = _SinkType
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
// Equatable types can be matched in patterns by value equality.
@_transparent
@warn_unused_result
public func ~= <T : Equatable> (a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++ {}
postfix operator -- {}
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator ! {}
// Standard prefix operators.
prefix operator ++ {}
prefix operator -- {}
prefix operator ! {}
prefix operator ~ {}
prefix operator + {}
prefix operator - {}
// Standard infix operators.
// "Exponentiative"
infix operator << { associativity none precedence 160 }
infix operator >> { associativity none precedence 160 }
// "Multiplicative"
infix operator * { associativity left precedence 150 }
infix operator &* { associativity left precedence 150 }
infix operator / { associativity left precedence 150 }
infix operator % { associativity left precedence 150 }
infix operator & { associativity left precedence 150 }
// "Additive"
infix operator + { associativity left precedence 140 }
infix operator &+ { associativity left precedence 140 }
infix operator - { associativity left precedence 140 }
infix operator &- { associativity left precedence 140 }
infix operator | { associativity left precedence 140 }
infix operator ^ { associativity left precedence 140 }
// FIXME: is this the right precedence level for "..." ?
infix operator ... { associativity none precedence 135 }
infix operator ..< { associativity none precedence 135 }
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as { associativity none precedence 132 }
// "Coalescing"
infix operator ?? { associativity right precedence 131 }
// "Comparative"
infix operator < { associativity none precedence 130 }
infix operator <= { associativity none precedence 130 }
infix operator > { associativity none precedence 130 }
infix operator >= { associativity none precedence 130 }
infix operator == { associativity none precedence 130 }
infix operator != { associativity none precedence 130 }
infix operator === { associativity none precedence 130 }
infix operator !== { associativity none precedence 130 }
// FIXME: ~= will be built into the compiler.
infix operator ~= { associativity none precedence 130 }
// "Conjunctive"
infix operator && { associativity left precedence 120 }
// "Disjunctive"
infix operator || { associativity left precedence 110 }
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : { associativity right precedence 100 }
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator = { associativity right precedence 90 }
// Compound
infix operator *= { associativity right precedence 90 assignment }
infix operator /= { associativity right precedence 90 assignment }
infix operator %= { associativity right precedence 90 assignment }
infix operator += { associativity right precedence 90 assignment }
infix operator -= { associativity right precedence 90 assignment }
infix operator <<= { associativity right precedence 90 assignment }
infix operator >>= { associativity right precedence 90 assignment }
infix operator &= { associativity right precedence 90 assignment }
infix operator ^= { associativity right precedence 90 assignment }
infix operator |= { associativity right precedence 90 assignment }
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~> { associativity left precedence 255 }
| apache-2.0 |