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 |
---|---|---|---|---|---|
kantega/tech-ex-2015 | ios/TechEx/lib/Almofire.swift | 2 | 67197 | // Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// 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
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)
}
}
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/// The URL string.
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: -
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
When finished with a manager, be sure to call either `session.finishTasksAndInvalidate()` or `session.invalidateAndCancel()` before deinitialization.
*/
public class Manager {
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
*/
public class var sharedInstance: Manager {
struct Singleton {
static var configuration: NSURLSessionConfiguration = {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders()
return configuration
}()
static let instance = Manager(configuration: configuration)
}
return Singleton.instance
}
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
:returns: The default header values.
*/
public class func defaultHTTPHeaders() -> [String: String] {
// Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}
private let delegate: SessionDelegate
private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}
// MARK: -
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask?
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask!)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if sessionDidReceiveChallenge != nil {
completionHandler(sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
private let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress? { return delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { (request, response, data) in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(delegate.queue) {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t
let progress: NSProgress
var data: NSData? { return nil }
private(set) var error: NSError?
var credential: NSURLCredential?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
return queue
}()
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
switch challenge.protectionSpace.authenticationMethod! {
case NSURLAuthenticationMethodServerTrust:
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
default:
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
}
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if error != nil {
self.error = error
}
dispatch_resume(queue)
}
}
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData? {
return mutableData
}
private var expectedContentLength: Int64?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
dataTaskDidReceiveData?(session, dataTask, data)
mutableData.appendData(data)
if let expectedContentLength = dataTask?.response?.expectedContentLength {
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
}
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Validation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
dispatch_async(delegate.queue) {
if self.response != nil && self.delegate.error == nil {
if !validation(self.request, self.response!) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
}
return self
}
// MARK: Status Code
private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
return contains(statusCodes, response.statusCode)
}
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate(statusCode range: Range<Int>) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
}
}
/**
Validates that the response has a status code in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: array The acceptable status codes.
:returns: The request.
*/
public func validate(statusCode array: [Int]) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: array)
}
}
// MARK: Content-Type
private struct MIMEType {
let type: String
let subtype: String
init(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
self.type = components.first!
self.subtype = components.last!
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
return true
default:
return false
}
}
}
private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
if response.MIMEType != nil {
let responseMIMEType = MIMEType(response.MIMEType!)
for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
if acceptableMIMEType.matches(responseMIMEType) {
return true
}
}
}
return false
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate(contentType array: [String]) -> Self {
return validate {(_, response) in
return Request.response(response, hasAcceptableContentType: array)
}
}
// MARK: Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: - Upload
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var HTTPBodyStream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = session.uploadTaskWithStreamedRequest(request)
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: stream The stream to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
}
extension Request {
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
// MARK: - Download
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = session.downloadTaskWithResumeData(resumeData)
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if downloadTaskDidFinishDownloadingToURL != nil {
let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port?.integerValue ?? 0, `protocol`: URL.scheme!, realm: URL.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if let cookieStorage = session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
if request.allHTTPHeaderFields != nil {
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if session.configuration.HTTPAdditionalHeaders != nil {
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let HTTPBody = request.HTTPBody {
if let escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") {
components.append("-d \"\(escapedBody)\"")
}
}
components.append("\"\(URL.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:returns: A string response serializer.
*/
public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
return { (_, _, data) in
let string = NSString(data: data!, encoding: encoding)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience -
private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: - Download
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
} | mit |
mayongl/CS193P | FaceIt/FaceIt/BlinkingFaceViewController.swift | 1 | 2319 | //
// BlinkingFaceViewController.swift
// FaceIt
//
// Created by Yonglin on 15/04/2017.
// Copyright © 2017 Yonglin. All rights reserved.
//
import UIKit
class BlinkingFaceViewController: FaceViewController {
var blinking = false {
didSet {
blinkIfNeeded()
}
}
override func updateUI() {
super.updateUI()
blinking = expression.eyes == .squinting
}
private struct BlinkRate {
static let closeDuration: TimeInterval = 0.4
static let openDuration: TimeInterval = 2.5
}
func blinkIfNeeded() {
if blinking && canBlink && !inABlink {
faceView.eyesOpen = false
inABlink = true
Timer.scheduledTimer(withTimeInterval: BlinkRate.closeDuration, repeats: false) { [weak self] timer in
self?.faceView.eyesOpen = true
Timer.scheduledTimer(withTimeInterval: BlinkRate.openDuration , repeats: false) { [weak self] timer in
self?.inABlink = false
self?.blinkIfNeeded()
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private var canBlink = false
private var inABlink = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
canBlink = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
canBlink = true
blinkIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
canBlink = false
}
/*
// 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.
}
*/
}
| apache-2.0 |
apple/swift | test/Migrator/fixit-NSObject-hashValue.swift | 32 | 407 | // RUN: %empty-directory(%t)
// RUN: not %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t/fixit-NSObject-hashValue.result
// RUN: diff -u %s.expected %t/fixit-NSObject-hashValue.result
// RUN: %target-swift-frontend -typecheck %s.expected
// REQUIRES: objc_interop
import ObjectiveC
class MyClass: NSObject {
override var hashValue: Int {
return 42
}
}
| apache-2.0 |
yarshure/Surf | Surf/LogListTableViewController.swift | 1 | 22168 | //
// LogListTableViewController.swift
// Surf
//
// Created by yarshure on 15/12/7.
// Copyright © 2015年 yarshure. All rights reserved.
//
import UIKit
import SFSocket
import SwiftyJSON
import XRuler
struct SFFILE {
var name:String
var date:NSDate
var size:Int64
init(n:String,d:NSDate,size:Int64){
name = n
date = d
self.size = size
}
var desc:String{
//print(size)
if size >= 1024 && size < 1024*1024 {
return "size: \(size/1024) KB"
}else if size >= 1024*1024 {
return "size: \(size/(1024*1024)) MB"
}else {
return "size: \(size) byte"
}
}
}
open class SFVPNStatisticsApp {
//public static let shared = SFVPNStatistics()
public var startDate = Date.init(timeIntervalSince1970: 0)
public var sessionStartTime = Date()
public var reportTime = Date.init(timeIntervalSince1970: 0)
public var startTimes = 0
public var show:Bool = false
public var totalTraffice:SFTraffic = SFTraffic()
public var currentTraffice:SFTraffic = SFTraffic()
public var lastTraffice:SFTraffic = SFTraffic()
public var maxTraffice:SFTraffic = SFTraffic()
public var wifiTraffice:SFTraffic = SFTraffic()
public var cellTraffice:SFTraffic = SFTraffic()
public var directTraffice:SFTraffic = SFTraffic()
public var proxyTraffice:SFTraffic = SFTraffic()
public var memoryUsed:UInt64 = 0
public var finishedCount:Int = 0
public var workingCount:Int = 0
public var runing:String {
get {
//let now = Date()
let second = Int(reportTime.timeIntervalSince(sessionStartTime))
return secondToString(second: second)
}
}
public func updateMax() {
if lastTraffice.tx > maxTraffice.tx{
maxTraffice.tx = lastTraffice.tx
}
if lastTraffice.rx > maxTraffice.rx {
maxTraffice.rx = lastTraffice.rx
}
}
public func secondToString(second:Int) ->String {
let sec = second % 60
let min = second % (60*60) / 60
let hour = second / (60*60)
return String.init(format: "%02d:%02d:%02d", hour,min,sec)
}
public func map(j:JSON) {
startDate = Date.init(timeIntervalSince1970: j["start"].doubleValue) as Date
sessionStartTime = Date.init(timeIntervalSince1970: j["sessionStartTime"].doubleValue)
reportTime = NSDate.init(timeIntervalSince1970: j["report_date"].doubleValue) as Date
totalTraffice.mapObject(j: j["total"])
lastTraffice.mapObject(j: j["last"])
maxTraffice.mapObject(j: j["max"])
cellTraffice.mapObject(j:j["cell"])
wifiTraffice.mapObject(j: j["wifi"])
directTraffice.mapObject(j: j["direct"])
proxyTraffice.mapObject(j: j["proxy"])
// if let c = j["memory"].uInt64 {
// memoryUsed = c
// }
// if let tcp = j["finishedCount"].int {
// finishedCount = tcp
// }
// if let tcp = j["workingCount"].int {
// workingCount = tcp
// }
}
func resport() ->Data{
//reportTime = Date()
//memoryUsed = reportMemoryUsed()//reportCurrentMemory()
var status:[String:AnyObject] = [:]
status["start"] = NSNumber.init(value: startDate.timeIntervalSince1970)
status["sessionStartTime"] = NSNumber.init(value: sessionStartTime.timeIntervalSince1970)
status["report_date"] = NSNumber.init(value: reportTime.timeIntervalSince1970)
//status["runing"] = NSNumber.init(double:runing)
status["total"] = totalTraffice.resp() as AnyObject?
status["last"] = lastTraffice.resp() as AnyObject?
status["max"] = maxTraffice.resp() as AnyObject?
status["memory"] = NSNumber.init(value: memoryUsed) //memoryUsed)
//let count = SFTCPConnectionManager.manager.connections.count
status["finishedCount"] = NSNumber.init(value: finishedCount) //
//status["workingCount"] = NSNumber.init(value: count) //
status["cell"] = cellTraffice.resp() as AnyObject?
status["wifi"] = wifiTraffice.resp() as AnyObject?
status["direct"] = directTraffice.resp() as AnyObject?
status["proxy"] = proxyTraffice.resp() as AnyObject?
let j = JSON(status)
//print("recentRequestData \(j)")
var data:Data
do {
try data = j.rawData()
}catch let error {
//AxLogger.log("ruleResultData error \(error.localizedDescription)")
//let x = error.localizedDescription
//let err = "report error"
data = error.localizedDescription.data(using: .utf8)!// NSData()
}
return data
}
public func memoryString() ->String {
let f = Float(memoryUsed)
if memoryUsed < 1024 {
return "\(memoryUsed) Bytes"
}else if memoryUsed >= 1024 && memoryUsed < 1024*1024 {
return String(format: "%.2f KB", f/1024.0)
}
return String(format: "%.2f MB", f/1024.0/1024.0)
}
}
class LogListTableViewController: SFTableViewController {
var filePath:String = ""
var fileList:[SFFILE] = []
var showSession:Bool = false
var reportInfo:SFVPNStatisticsApp?
override func viewDidLoad() {
super.viewDidLoad()
if filePath.isEmpty {
self.title = "Sessions"
}else {
self.title = "Session Detail"
showSession = true
}
findFiles()
navigationItem.rightBarButtonItem = editButtonItem
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func deleteAll(_ sender:AnyObject) {
if let m = SFVPNManager.shared.manager , m.connection.status == .connected {
for file in fileList.dropFirst() {
let url = groupContainerURL().appendingPathComponent("Log/"+file.name)
do {
try fm.removeItem(at: url)
}catch let error as NSError {
alertMessageAction("delete \(url.path) failure: \(error.description)",complete: nil)
return
}
}
}else {
for file in fileList {
let url = groupContainerURL().appendingPathComponent("Log/"+file.name)
do {
try fm.removeItem(at: url)
}catch let error as NSError {
alertMessageAction("delete \(url.path) failure: \(error.description)",complete: nil)
return
}
}
}
findFiles()
}
func findFiles(){
let q = DispatchQueue(label:"com.yarshure.sortlog")
q.async(execute: { [weak self] () -> Void in
self!.fileList.removeAll()
//let urlContain = FileManager.default.containerURLForSecurityApplicationGroupIdentifier("group.com.yarshure.Surf")
let url = groupContainerURL().appendingPathComponent("Log/" + self!.filePath)
let dir = url.path //NSHomeDirectory().NS.stringByAppendingPathComponent("Documents/applog")
if FileManager.default.fileExists(atPath:dir) {
let files = try! FileManager.default.contentsOfDirectory(atPath: dir)
var tmpArray:[SFFILE] = []
for file in files {
let url = url.appendingPathComponent(file)
let att = try! fm.attributesOfItem(atPath: url.path)
let d = att[ FileAttributeKey.init("NSFileCreationDate")] as! NSDate
let size = att[FileAttributeKey.init("NSFileSize")]! as! NSNumber
let fn = SFFILE.init(n: file, d: d,size:size.int64Value)
tmpArray.append(fn)
}
tmpArray.sort(by: { $0.date.compare($1.date as Date) == ComparisonResult.orderedDescending })
DispatchQueue.main.async(execute: {
if let strongSelf = self {
strongSelf.fileList.append(contentsOf: tmpArray)
if strongSelf.showSession {
strongSelf.loadReport()
}else {
strongSelf.tableView.reloadData()
}
}
})
}else {
}
})
//fileList = try! FileManager.default.contentsOfDirectoryAtURL(url, includingPropertiesForKeys keys: [String]?, options mask: NSDirectoryEnumerationOptions) throws -> [NSURL]
}
func loadReport(){
let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/db.zip")
let urlJson = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/session.json")
if FileManager.default.fileExists(atPath: urlJson.path){
reportInfo = SFVPNStatisticsApp()//.init(name: self.filePath)
do {
let data = try Data.init(contentsOf: urlJson)
let obj = try! JSON.init(data: data)
reportInfo!.map(j: obj)
tableView.reloadData()
return
}catch let e {
alertMessageAction("\(e.localizedDescription)", complete: nil)
}
}
if FileManager.default.fileExists(atPath: url.path){
let _ = RequestHelper.shared.openForApp(self.filePath)
let resultsFin = RequestHelper.shared.fetchAll()
reportInfo = SFVPNStatisticsApp()//.init(name: self.filePath)
for req in resultsFin {
reportInfo?.totalTraffice.addRx(x:Int(req.traffice.rx) )
reportInfo?.totalTraffice.addTx(x:Int(req.traffice.tx) )
if req.interfaceCell == 1 {
reportInfo?.cellTraffice.addRx(x: Int(req.traffice.rx))
reportInfo?.cellTraffice.addTx(x: Int(req.traffice.tx))
}else {
reportInfo?.wifiTraffice.addRx(x: Int(req.traffice.rx))
reportInfo?.wifiTraffice.addTx(x: Int(req.traffice.tx))
}
if req.rule.policy == .Direct {
reportInfo?.directTraffice.addRx(x: Int(req.traffice.rx))
reportInfo?.directTraffice.addTx(x: Int(req.traffice.tx))
}else {
reportInfo?.proxyTraffice.addRx(x: Int(req.traffice.rx))
reportInfo?.proxyTraffice.addTx(x: Int(req.traffice.tx))
}
if req.sTime.compare(reportInfo!.sessionStartTime) == .orderedAscending{
reportInfo!.sessionStartTime = req.sTime
}
if req.eTime.compare(reportInfo!.reportTime) == .orderedDescending {
reportInfo!.reportTime = req.eTime
}
}
let data = reportInfo!.resport()
let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/session.json")
do {
try data.write(to:url )
} catch let e {
alertMessageAction("\(e.localizedDescription)", complete: nil)
}
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if filePath.isEmpty {
let dir = fileList[indexPath.row]
print(dir)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "filelist") as! LogListTableViewController
vc.filePath = dir.name
self.navigationController?.pushViewController(vc, animated: true)
}else {
let cell = tableView.cellForRow(at: indexPath)
if indexPath.row > fileList.count {
self.performSegue(withIdentifier: "showFile", sender: cell)
}else {
let f = fileList[indexPath.row]
if f.name == "db.zip" {
self.performSegue(withIdentifier: "showDB", sender: cell)
}else {
self.performSegue(withIdentifier: "showFile", sender: cell)
}
}
}
}
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 {
// #warning Incomplete implementation, return the number of sections
if filePath.isEmpty {
if fileList.count == 0 {
return 1
}
return 2
}else {
return 2
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
if fileList.count == 0 {
return 1
}
return fileList.count
}else {
if showSession {
if let _ = reportInfo{
return 6
}else {
return 0
}
}else {
return 1
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "logidentifier", for: indexPath as IndexPath)
if fileList.count == 0 {
cell.textLabel?.text = "No log files"
cell.detailTextLabel?.text = ""
}else {
// Configure the cell...
//bug
if indexPath.row < fileList.count {
let f = fileList[indexPath.row]
cell.textLabel?.text = f.name
if !filePath.isEmpty {
cell.detailTextLabel?.text = f.desc
}else {
cell.detailTextLabel?.text = ""
}
}
}
cell.updateStandUI()
return cell
}else {
if showSession {
let cell = tableView.dequeueReusableCell(withIdentifier: "StatusCell", for: indexPath as IndexPath) as! StatusCell
guard let r = self.reportInfo else {
return cell
}
configCell(cell: cell,indexPath: indexPath, report: r)
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "deleteAll", for: indexPath as IndexPath)
return cell
}
}
}
func configCell(cell:StatusCell, indexPath:IndexPath,report:SFVPNStatisticsApp){
let flag = true
let f = UIFont.init(name: "Ionicons", size: 20)!
cell.downLabel.text = "\u{f35d}"
cell.downLabel.font = f
cell.upLabel.text = "\u{f366}"
cell.upLabel.font = f
cell.updateUI()
switch indexPath.row {
case 0:
cell.catLabel.text = "\u{f3b3}"
cell.downInfoLabel.isHidden = true //report.memoryString()
cell.downLabel.isHidden = true
cell.upLabel.isHidden = true
cell.upInfoLabel.text = report.runing
return
case 1:
cell.catLabel.text = "\u{f37c}"
//cell.textLabel?.text = "Total: \(report.totalTraffice.reportTraffic())"
cell.upInfoLabel.text = report.totalTraffice.toString(x: report.totalTraffice.tx,label: "",speed: false)
cell.downInfoLabel.text = report.totalTraffice.toString(x: report.totalTraffice.rx,label: "",speed: false)
case 2:
cell.upInfoLabel.text = report.directTraffice.toString(x: report.directTraffice.tx,label: "",speed: false)
cell.downInfoLabel.text = report.directTraffice.toString(x: report.directTraffice.rx,label: "",speed: false)
cell.catLabel.text = "\u{f394}"//cell.textLabel?.text = "DIRECT: \(report.directTraffice.reportTraffic())"
case 3:
//cell.textLabel?.text = "PROXY: \(report.proxyTraffice.reportTraffic())"
cell.catLabel.text = "\u{f4a8}"
cell.upInfoLabel.text = report.proxyTraffice.toString(x: report.proxyTraffice.tx,label: "",speed: false)
cell.downInfoLabel.text = report.proxyTraffice.toString(x: report.proxyTraffice.rx,label: "",speed: false)
case 4:
//cell.textLabel?.attributedText = report.wifi()
cell.upInfoLabel.text = report.wifiTraffice.toString(x: report.wifiTraffice.tx,label: "",speed: false)
cell.downInfoLabel.text = report.wifiTraffice.toString(x: report.wifiTraffice.rx,label: "",speed: false)
cell.catLabel.text = "\u{f25c}"
case 5:
//cell.textLabel?.text = "CELL: \(report.cellTraffice.reportTraffic())"
cell.upInfoLabel.text = report.cellTraffice.toString(x: report.cellTraffice.tx,label: "",speed: false)
cell.downInfoLabel.text = report.cellTraffice.toString(x: report.cellTraffice.rx,label: "",speed: false)
cell.catLabel.text = "\u{f274}"
default:
break
}
/*
if flag {
//print("TCP Connection: \(report.connectionCount) memory:\(report.memoryUsed) ")
}else {
cell.textLabel?.text = "Session Not Start"
cell.catLabel.isHidden = true
cell.downLabel.isHidden = true
cell.downInfoLabel.isHidden = true
cell.upLabel.isHidden = true
cell.upInfoLabel.isHidden = true
}*/
cell.downLabel.isHidden = false
cell.upLabel.isHidden = false
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0 && fileList.count == 0 {
return nil
}
if indexPath.section == 1 {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.row == 0 {
guard let m = SFVPNManager.shared.manager else {return true}
if m.connection.status == .connected {
return false
}else {
if fileList.count == 0 {
return false
}
return true
}
}
return true
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.item < fileList.count {
return .delete
}
return .delete
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
let f = fileList[indexPath.row]
let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/" + f.name)
//saveProxys()
do {
try fm.removeItem(at: url)
fileList.remove(at: indexPath.row)
} catch _ {
}
tableView.reloadData()
}
}
// 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.destination.
// Pass the selected object to the new view controller.
if segue.identifier == "showFile"{
guard let addEditController = segue.destination as? LogFileViewController else{return}
let cell = sender as? UITableViewCell
guard let indexPath = tableView.indexPath(for: cell!) else {return }
let f = fileList[indexPath.row]
addEditController.navigationItem.title = f.name
let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/" + f.name)
addEditController.filePath = url
// addEditController.delegate = self
}else if segue.identifier == "showDB" {
guard let vc = segue.destination as? HistoryViewController else{return}
vc.session = self.filePath
}
}
}
| bsd-3-clause |
wowiwj/WDayDayCook | WDayDayCook/WDayDayCook/Controllers/Choose/ChooseViewController.swift | 1 | 11413 | //
// ChooseViewController.swift
// WDayDayCook
//
// Created by wangju on 16/7/24.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import RealmSwift
import SDCycleScrollView
let cellIdentifier = "MyCollectionCell"
let ThemeListTableViewCellID = "ThemeListTableViewCell"
let RecipeDiscussListTableViewCellID = "RecipeDiscussListTableViewCell"
final class ChooseViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!{
didSet{
tableView.backgroundColor = UIColor.white
tableView.register(MyCollectionCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.register(ThemeListTableViewCell.self, forCellReuseIdentifier: ThemeListTableViewCellID)
tableView.register(RecipeDiscussListTableViewCell.self, forCellReuseIdentifier: RecipeDiscussListTableViewCellID)
tableView.separatorStyle = .none
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
tableView.estimatedRowHeight = 250
}
}
fileprivate lazy var titleView :UIImageView = {
let titleView = UIImageView()
titleView.image = UIImage(named: "navi_logo~iphone")
titleView.sizeToFit()
return titleView
}()
fileprivate var realm: Realm!
// 广告数据
fileprivate lazy var adData: Results<MainADItem> = {
return getADItemInRealm(self.realm)
}()
// 每日新品数据
fileprivate var newFoodItems: Results<NewFood>?{
didSet{
tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
}
}
/// 主题推荐
fileprivate var themeList: Results<FoodRecmmand>?
/// 热门推荐
fileprivate var recipeList: Results<FoodRecmmand>?
/// 话题推荐
fileprivate var recipeDiscussList: Results<FoodRecmmand>?
// tabble头部
var cycleView: SDCycleScrollView?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = titleView
let searchButton = UIBarButtonItem(image: UIImage(named: "icon-search~iphone"), style: .plain, target: self, action: #selector(searchButtonClicked(_:)))
navigationItem.rightBarButtonItem = searchButton
realm = try! Realm()
let placeholderImage = UIImage(named: "default_1~iphone")!
let images = realm.objects(MainADItem.self).map { item -> String in
return item.path
}
cycleView = SDCycleScrollView(frame: CGRect(origin: CGPoint.zero, size: placeholderImage.size), delegate: self, placeholderImage: placeholderImage)
//cycleView!.imageURLStringsGroup = images
tableView.tableHeaderView = cycleView
tableView.addHeaderWithCallback {
let group = DispatchGroup()
let queue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default)
queue.async(group: group) {
self.loadADData()
}
queue.async(group: group) {
self.loadNewFoodEachDay(0, pageSize: 10)
}
group.notify(queue: queue) {
self.loadRecommandInfo()
}
}
self.tableView.headerBeginRefreshing()
// self.tableView.addEmptyDataSetView { (set) in
// set.image = UIImage(named: "666")
// }
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.navigationController?.navigationBar.hidden = false
}
// MARK: - LoadData
/// 加载上方滚动广告
func loadADData(){
Alamofire.request(Router.chooseViewAdList(parameters: nil)).responseJSON { [unowned self] responses in
if responses.result.isFailure
{
WDAlert.alertSorry(message: "网络异常", inViewController: self)
// 加载失败,使用旧数据
return
}
let json = responses.result.value
let result = JSON(json!)
deleteAllADItem()
addNewMainADItemInRealm(result["data"])
// 加载成功,使用新数据
self.adData = getADItemInRealm(self.realm)
self.cycleView?.imageURLStringsGroup = self.realm.objects(MainADItem.self).map { item -> String in
return item.path
}
}
}
// 加载每日新品
func loadNewFoodEachDay(_ currentPage:Int,pageSize:Int)
{
Alamofire.request(Router.newFoodEachDay(currentpage: currentPage, pageSize: pageSize)).responseJSON { [unowned self] response in
if response.result.isFailure
{
WDAlert.alertSorry(message: "网络异常", inViewController: self)
// 获取离线数据
self.newFoodItems = getNewFoodItemInRealm(self.realm)
return
}
let value = response.result.value
let result = JSON(value!)
deleteAllObject(NewFood.self)
addNewFoodItemInRealm(result["data"])
self.newFoodItems = getNewFoodItemInRealm(self.realm)
}
}
/// 加载推荐信息数据
func loadRecommandInfo()
{
Alamofire.request(Router.recommendInfo(parameters: nil)).responseJSON {[unowned self] response in
self.tableView.headerEndRefreshing()
func getFoodRecmmand()
{
self.themeList = getThemeListInRealm(self.realm)
self.recipeList = getRecipeListInRealm(self.realm)
self.recipeDiscussList = getRecipeDiscussListInRealm(self.realm)
self.tableView.reloadData()
}
if response.result.isFailure
{
print(response.request)
print(response.result.error)
WDAlert.alertSorry(message: "网络异常", inViewController: self)
getFoodRecmmand()
return
}
let value = response.result.value
let result = JSON(value!)
func updateFoodRecmmand()
{
// 删除之前存的旧数据
deleteAllObject(FoodRecmmand.self)
// 添加新数据到数据库
addFoodRecmmandItemInRealm(result["themeList"])
addFoodRecmmandItemInRealm(result["recipeList"])
addFoodRecmmandItemInRealm(result["recipeDiscussList"])
}
updateFoodRecmmand()
getFoodRecmmand()
}
}
// MARK: - 控制器跳转
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else{
return
}
if identifier == "showDetail" {
let vc = segue.destination as! ShowDetailViewController
let item = sender as! Int
vc.id = item
}
}
// MARK: - 动作监听
@objc fileprivate func searchButtonClicked(_ button:UIButton)
{
}
}
// MARK: - UITableViewDelegate,UITableViewDataSource
extension ChooseViewController:UITableViewDelegate,UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if recipeDiscussList == nil {
return 3
}
return recipeDiscussList!.count > 0 ? 4 : 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath as NSIndexPath).row {
case CellStyle.themeList.rawValue:
let cell =
tableView.dequeueReusableCell(withIdentifier: ThemeListTableViewCellID)! as! ThemeListTableViewCell
cell.delegate = self
return cell
case CellStyle.recipeDiscussList.rawValue:
let cell =
tableView.dequeueReusableCell(withIdentifier: RecipeDiscussListTableViewCellID)!
return cell
default:
let cell =
tableView.dequeueReusableCell(withIdentifier: cellIdentifier)! as! MyCollectionCell
cell.delegate = self
return cell
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
switch (indexPath as NSIndexPath).row {
case CellStyle.newFood.rawValue:
let newFoodcell = cell as! MyCollectionCell
newFoodcell.newFoodItems = newFoodItems
case CellStyle.themeList.rawValue:
let cell = cell as! ThemeListTableViewCell
cell.themeList = themeList
case CellStyle.recipeList.rawValue:
let cell = cell as! MyCollectionCell
cell.recipeList = recipeList
default:
let cell = cell as! RecipeDiscussListTableViewCell
cell.recipeDiscussList = recipeDiscussList
}
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// let cell = cell as! MyCollectionCell
// cell.collectionView.frame = CGRectZero
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch (indexPath as NSIndexPath).row {
case CellStyle.themeList.rawValue:
return CGFloat(themeList?.count ?? 0).autoAdjust() * WDConfig.themeListHeight + 30
case CellStyle.recipeDiscussList.rawValue:
return CGFloat(200).autoAdjust()
default:
return CGFloat(280).autoAdjust()
}
}
}
extension ChooseViewController : SDCycleScrollViewDelegate
{
func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
let item = adData[index]
performSegue(withIdentifier: "showDetail", sender: Int(item.url))
}
}
extension ChooseViewController :MyCollectionCellDelegete,ThemeListTableViewCellDelagate
{
func didSeclectItem(_ item: Object) {
if item is NewFood
{
performSegue(withIdentifier: "showDetail", sender: (item as! NewFood).id)
}
if item is FoodRecmmand{
performSegue(withIdentifier: "showDetail", sender: (item as! FoodRecmmand).recipe_id)
}
if item is FoodRecmmand {
}
}
}
| mit |
Eonil/Editor | Editor4/WorkspaceWindowController.swift | 1 | 3799 | //
// WorkspaceWindowController.swift
// Editor4
//
// Created by Hoon H. on 2016/04/20.
// Copyright © 2016 Eonil. All rights reserved.
//
import Foundation
import AppKit
import EonilToolbox
private struct LocalState {
var workspaceID: WorkspaceID?
}
final class WorkspaceWindowController: NSWindowController, DriverAccessible, WorkspaceRenderable {
private let columnSplitViewController = NSSplitViewController()
private let navigatorViewController = NavigatorViewController()
private let rowSplitViewController = NSSplitViewController()
private let dummy1ViewController = WorkspaceRenderableViewController()
private var installer = ViewInstaller()
private var localState = LocalState()
////////////////////////////////////////////////////////////////
/// Designated initializer.
init() {
let newWindow = WorkspaceWindow()
newWindow.appearance = NSAppearance(named: NSAppearanceNameVibrantDark)
newWindow.styleMask |= NSClosableWindowMask | NSResizableWindowMask | NSTitledWindowMask
super.init(window: newWindow)
// newWindow.display()
// newWindow.makeKeyAndOrderFront(self)
// let newWorkspaceViewController = WorkspaceViewController()
// workspaceViewController = newWorkspaceViewController
// contentViewController = newWorkspaceViewController
shouldCloseDocument = false
NotificationUtility.register(self, NSWindowWillCloseNotification, self.dynamicType.process)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationUtility.deregister(self)
}
////////////////////////////////////////////////////////////////
func render(state: UserInteractionState, workspace: (id: WorkspaceID, state: WorkspaceState)?) {
renderLocalState()
contentViewController?.renderRecursively(state, workspace: workspace)
}
private func renderLocalState() {
installer.installIfNeeded {
// assert(columnSplitViewController.view.autoresizesSubviews == false)
// assert(rowSplitViewController.view.autoresizesSubviews == false)
contentViewController = columnSplitViewController
columnSplitViewController.view.autoresizesSubviews = false
columnSplitViewController.splitViewItems = [
NSSplitViewItem(contentListWithViewController: navigatorViewController),
NSSplitViewItem(viewController: rowSplitViewController),
]
rowSplitViewController.view.autoresizesSubviews = false
rowSplitViewController.splitViewItems = [
NSSplitViewItem(viewController: dummy1ViewController),
]
}
localState.workspaceID = localState.workspaceID
}
private func process(n: NSNotification) {
switch n.name {
case NSWindowWillCloseNotification:
guard n.object === window else { return }
guard let workspaceID = localState.workspaceID else { return }
driver.operation.closeWorkspace(workspaceID)
default:
break
}
}
}
extension WorkspaceWindowController {
override var shouldCloseDocument: Bool {
willSet {
assert(newValue == false)
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private final class WorkspaceWindow: NSWindow {
override var canBecomeMainWindow: Bool {
get {
return true
}
}
}
| mit |
LawrenceHan/iOS-project-playground | Chatter/ChatterUITests/ChatterUITests.swift | 1 | 1239 | //
// ChatterUITests.swift
// ChatterUITests
//
// Created by Hanguang on 12/11/15.
// Copyright © 2015 Hanguang. All rights reserved.
//
import XCTest
class ChatterUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
totomo/SSLogger | SSLoggerSample/ViewController.swift | 1 | 758 | //
// ViewController.swift
// SSLoggerSample
//
// Created by Kenta Tokumoto on 2015/09/19.
// Copyright © 2015年 Kenta Tokumoto. All rights reserved.
//
import UIKit
import SSLogger
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let integer:Int? = 123456
let string:String? = nil
let boolean:Bool? = false
print(integer, string, boolean)
print("integer: \(integer)\nstring: \(string) \nboolean: \(boolean)")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
krzysztofzablocki/Sourcery | Sourcery/Generating/Templates/Stencil/StencilTemplate.swift | 1 | 368 | import Foundation
import SourceryFramework
import SourceryRuntime
import SourceryStencil
extension StencilTemplate: SourceryFramework.Template {
public func render(_ context: TemplateContext) throws -> String {
do {
return try self.render(context.stencilContext)
} catch {
throw "\(sourcePath): \(error)"
}
}
}
| mit |
kyleoshaughnessy/DaylightView | DaylightViewTests/DaylightViewTests.swift | 1 | 918 | //
// DaylightViewTests.swift
// DaylightViewTests
//
// Created by Kyle on 2015-12-19.
// Copyright (c) 2015 Kyle O'Shaughnessy. All rights reserved.
//
import Cocoa
import XCTest
class DaylightViewTests: 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.
}
}
}
| gpl-3.0 |
ryanspillsbury90/HaleMeditates | ios/Hale Meditates/CallToActionViewController.swift | 1 | 1622 | //
// CallToActionViewController.swift
// Hale Meditates
//
// Created by Ryan Pillsbury on 6/27/15.
// Copyright (c) 2015 koait. All rights reserved.
//
import UIKit
class CallToActionViewController: UIViewController {
@IBOutlet weak var proportialConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad();
self.navigationItem.title = "Home";
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true);
super.viewWillAppear(animated);
}
@IBAction func openGoPremiumWebPage() {
let controller = UIUtil.getViewControllerFromStoryboard("WebViewController") as! WebViewController
if let URL = NSURL(string: "http://www.wired.com") {
controller.url = URL;
controller.view.frame = self.navigationController!.view.frame;
self.presentViewController(controller, animated: true, completion: nil);
}
}
/*
// 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 |
sergiog90/Strategy-Pattern-iOS | swift/swift-strategy-pattern/Models/PictureList.swift | 1 | 308 | //
// PictureList.swift
// swift-strategy-pattern
//
// Created by Sergio Garcia on 17/7/15.
// Copyright (c) 2015 Sergio Garcia. All rights reserved.
//
import UIKit
class PictureList: NSObject {
var images: [String]
init(images: [String]) {
self.images = images
}
}
| mit |
khoren93/SwiftHub | SwiftHub/Modules/Issues/IssueCell.swift | 1 | 682 | //
// IssueCell.swift
// SwiftHub
//
// Created by Sygnoos9 on 11/20/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import UIKit
import RxSwift
class IssueCell: DefaultTableViewCell {
override func makeUI() {
super.makeUI()
titleLabel.numberOfLines = 2
}
override func bind(to viewModel: TableViewCellViewModel) {
super.bind(to: viewModel)
guard let viewModel = viewModel as? IssueCellViewModel else { return }
cellDisposeBag = DisposeBag()
leftImageView.rx.tap().map { _ in viewModel.issue.user }.filterNil()
.bind(to: viewModel.userSelected).disposed(by: cellDisposeBag)
}
}
| mit |
tjw/swift | test/Constraints/overload.swift | 4 | 6073 | // RUN: %target-typecheck-verify-swift
func markUsed<T>(_ t: T) {}
func f0(_: Float) -> Float {}
func f0(_: Int) -> Int {}
func f1(_: Int) {}
func identity<T>(_: T) -> T {}
func f2<T>(_: T) -> T {}
// FIXME: Fun things happen when we make this T, U!
func f2<T>(_: T, _: T) -> (T, T) { }
struct X {}
var x : X
var i : Int
var f : Float
_ = f0(i)
_ = f0(1.0)
_ = f0(1)
f1(f0(1))
f1(identity(1))
f0(x) // expected-error{{cannot invoke 'f0' with an argument list of type '(X)'}}
// expected-note @-1 {{overloads for 'f0' exist with these partially matching parameter lists: (Float), (Int)}}
_ = f + 1
_ = f2(i)
_ = f2((i, f))
class A {
init() {}
}
class B : A {
override init() { super.init() }
}
class C : B {
override init() { super.init() }
}
func bar(_ b: B) -> Int {} // #1
func bar(_ a: A) -> Float {} // #2
var barResult = bar(C()) // selects #1, which is more specialized
i = barResult // make sure we got #1
f = bar(C()) // selects #2 because of context
// Overload resolution for constructors
protocol P1 { }
struct X1a : P1 { }
struct X1b {
init(x : X1a) { }
init<T : P1>(x : T) { }
}
X1b(x: X1a()) // expected-warning{{unused}}
// Overload resolution for subscript operators.
class X2a { }
class X2b : X2a { }
class X2c : X2b { }
struct X2d {
subscript (index : X2a) -> Int {
return 5
}
subscript (index : X2b) -> Int {
return 7
}
func foo(_ x : X2c) -> Int {
return self[x]
}
}
// Invalid declarations
// FIXME: Suppress the diagnostic for the call below, because the invalid
// declaration would have matched.
func f3(_ x: Intthingy) -> Int { } // expected-error{{use of undeclared type 'Intthingy'}}
func f3(_ x: Float) -> Float { }
f3(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
func f4(_ i: Wonka) { } // expected-error{{use of undeclared type 'Wonka'}}
func f4(_ j: Wibble) { } // expected-error{{use of undeclared type 'Wibble'}}
f4(5)
func f1() {
var c : Class // expected-error{{use of undeclared type 'Class'}}
markUsed(c.x) // make sure error does not cascade here
}
// We don't provide return-type sensitivity unless there is context.
func f5(_ i: Int) -> A { return A() } // expected-note{{candidate}}
func f5(_ i: Int) -> B { return B() } // expected-note{{candidate}}
f5(5) // expected-error{{ambiguous use of 'f5'}}
struct HasX1aProperty {
func write(_: X1a) {}
func write(_: P1) {}
var prop = X1a()
func test() {
write(prop) // no error, not ambiguous
}
}
// rdar://problem/16554496
@available(*, unavailable)
func availTest(_ x: Int) {}
func availTest(_ x: Any) { markUsed("this one") }
func doAvailTest(_ x: Int) {
availTest(x)
}
// rdar://problem/20886179
func test20886179(_ handlers: [(Int) -> Void], buttonIndex: Int) {
handlers[buttonIndex](buttonIndex)
}
// The problem here is that the call has a contextual result type incompatible
// with *all* overload set candidates. This is not an ambiguity.
func overloaded_identity(_ a : Int) -> Int {}
func overloaded_identity(_ b : Float) -> Float {}
func test_contextual_result_1() {
return overloaded_identity() // expected-error {{cannot invoke 'overloaded_identity' with no arguments}}
// expected-note @-1 {{overloads for 'overloaded_identity' exist with these partially matching parameter lists: (Int), (Float)}}
}
func test_contextual_result_2() {
return overloaded_identity(1) // expected-error {{unexpected non-void return value in void function}}
}
// rdar://problem/24128153
struct X0 {
init(_ i: Any.Type) { }
init?(_ i: Any.Type, _ names: String...) { }
}
let x0 = X0(Int.self)
let x0check: X0 = x0 // okay: chooses first initializer
struct X1 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, _ names: String...) { }
}
let x1 = X1(Int.self)
let x1check: X1 = x1 // expected-error{{value of optional type 'X1?' not unwrapped; did you mean to use '!' or '?'?}}
struct X2 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, a: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, b: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, c: Int = 0) { }
}
let x2 = X2(Int.self)
let x2check: X2 = x2 // expected-error{{value of optional type 'X2?' not unwrapped; did you mean to use '!' or '?'?}}
// rdar://problem/28051973
struct R_28051973 {
mutating func f(_ i: Int) {}
@available(*, deprecated, message: "deprecated")
func f(_ f: Float) {}
}
let r28051973: Int = 42
R_28051973().f(r28051973) // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}}
// Fix for CSDiag vs CSSolver disagreement on what constitutes a
// valid overload.
func overloadedMethod(n: Int) {} // expected-note {{'overloadedMethod(n:)' declared here}}
func overloadedMethod<T>() {}
// expected-error@-1 {{generic parameter 'T' is not used in function signature}}
overloadedMethod()
// expected-error@-1 {{missing argument for parameter 'n' in call}}
// Ensure we select the overload of '??' returning T? rather than T.
func SR3817(_ d: [String : Any], _ s: String, _ t: String) -> Any {
if let r = d[s] ?? d[t] {
return r
} else {
return 0
}
}
// Overloading with mismatched labels.
func f6<T>(foo: T) { }
func f6<T: P1>(bar: T) { }
struct X6 {
init<T>(foo: T) { }
init<T: P1>(bar: T) { }
}
func test_f6() {
let _: (X1a) -> Void = f6
let _: (X1a) -> X6 = X6.init
}
func curry<LHS, RHS, R>(_ f: @escaping (LHS, RHS) -> R) -> (LHS) -> (RHS) -> R {
return { lhs in { rhs in f(lhs, rhs) } }
}
// We need to have an alternative version of this to ensure that there's an overload disjunction created.
func curry<F, S, T, R>(_ f: @escaping (F, S, T) -> R) -> (F) -> (S) -> (T) -> R {
return { fst in { snd in { thd in f(fst, snd, thd) } } }
}
// Ensure that we consider these unambiguous
let _ = curry(+)(1)
let _ = [0].reduce(0, +)
let _ = curry(+)("string vs. pointer")
func autoclosure1<T>(_: T, _: @autoclosure () -> X) { }
func autoclosure1<T>(_: [T], _: X) { }
func test_autoclosure1(ia: [Int]) {
autoclosure1(ia, X()) // okay: resolves to the second function
}
| apache-2.0 |
noxytrux/DateFormatter | DateFormatterTests/DateFormatterTests.swift | 1 | 931 | //
// DateFormatterTests.swift
// DateFormatterTests
//
// Created by Marcin Pędzimąż on 05.08.2015.
// Copyright (c) 2015 Marcin Małysz. All rights reserved.
//
import UIKit
import XCTest
class DateFormatterTests: 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 |
quran/quran-ios | Sources/BatchDownloader/Utilities.swift | 1 | 378 | //
// Utilities.swift
//
//
// Created by Mohamed Afifi on 2021-12-31.
//
import Foundation
import PromiseKit
extension NetworkSession {
func tasks() -> Guarantee<([NetworkSessionDataTask], [NetworkSessionUploadTask], [NetworkSessionDownloadTask])> {
Guarantee { resolver in
getTasksWithCompletionHandler { resolver(($0, $1, $2)) }
}
}
}
| apache-2.0 |
roambotics/swift | test/SymbolGraph/Symbols/Mixins/Availability/Duplicated/IntroducedFilled.swift | 20 | 758 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name IntroducedFilled -emit-module -emit-module-path %t/
// RUN: %target-swift-symbolgraph-extract -module-name IntroducedFilled -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/IntroducedFilled.symbols.json
// REQUIRES: OS=macosx
@available(macOS, deprecated: 10.0)
@available(macOS, introduced: 10.0)
public func foo() {}
// This effectively erases the deprecation.
// CHECK: "precise": "s:16IntroducedFilled3fooyyF"
// CHECK: "availability": [
// CHECK-NEXT: {
// CHECK-NEXT: "domain": "macOS",
// CHECK-NEXT: "introduced": {
// CHECK-NEXT: "major": 10,
// CHECK-NEXT: "minor": 0
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
| apache-2.0 |
nathawes/swift | test/SourceKit/Refactoring/syntactic-rename.swift | 9 | 7176 | struct AStruct {
/**
A description
- parameter a: The first param
*/
func foo(a: Int) -> Int {
let z = a + 1
#if true
return z
#else
return z + 1
#endif
}
}
let aStruct = AStruct()
let x = aStruct.foo(a: 2)
let y = AStruct.foo(aStruct)(a: 3)
print(x + 2)
print(y + 1)
let s = "a foo is here"
#selector(AStruct.foo(a:))
#selector(AStruct.foo())
#selector(AStruct.foo)
let y = "before foo \(foo(a:1)) foo after foo"
func bar(a/* a comment */: Int, b c: Int, _: Int, _ d: Int) {}
bar(a: 1, b: 2, 3, 4)
/// a comment named example
func example() {}
/// another comment named example
class Example {}
class Init {
init(x: Int) {}
}
_ = Init(x: 1)
enum MyEnum {
case first
case second(Int)
case third(x: Int)
case fourth(x: Int, y: Int, Int)
}
let first = MyEnum.first
let second = MyEnum.second(2)
let _ = MyEnum.second(_: 2)
let third = MyEnum.third(x: 1)
let fourth = MyEnum.fourth(x: 1, y: 2, 3)
switch fourth {
case .first:
print(1)
case .second(_: let x):
print(x)
case .third(x: let x):
print(x)
case .fourth(let x, y: let y, _: let z):
print(x + y + z)
}
struct Memberwise1 {
let x: Int
let y = 0
}
struct Memberwise2 {
let m: Memberwise1
let n: Memberwise1; subscript(x: Int) -> Int { return x }
}
_ = Memberwise2(m: Memberwise1(x: 1), n: Memberwise1.init(x: 2))[1]
protocol Layer {
associatedtype Content
}
struct MultiPaneLayout<A: Layer, B: Layer>: Layer where A.Content == B.Content{
typealias Content = Int
}
protocol P {}
struct S {
subscript<K: P>(key: K) -> Int {
return 0
}
}
protocol Q {}
func genfoo<T: P, U, V where U: P>(x: T, y: U, z: V, a: P) -> P where V: P {
fatalError()
}
_ = Memberwise1(x: 2)
_ = Memberwise1.init(x: 2)
_ = Memberwise2.init(m: Memberwise1(x: 2), n: Memberwise1(x: 34))
_ = " this init is init "
// this init is init too
#if NOTDEFINED
_ = Memberwise1(x: 2)
_ = Memberwise1.init(x: 2)
_ = Memberwise2.init(m: 2, n: Memberwise1(x: 34))
#endif
// RUN: %empty-directory(%t.result)
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/x.in.json %s >> %t.result/x.expected
// RUN: %diff -u %S/syntactic-rename/x.expected %t.result/x.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/z.in.json %s >> %t.result/z.expected
// RUN: %diff -u %S/syntactic-rename/z.expected %t.result/z.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/foo.in.json %s >> %t.result/foo_arity1.expected
// RUN: %diff -u %S/syntactic-rename/foo_arity1.expected %t.result/foo_arity1.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/foo_remove.in.json %s >> %t.result/foo_remove.expected
// RUN: %diff -u %S/syntactic-rename/foo_remove.expected %t.result/foo_remove.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar.in.json %s >> %t.result/bar.expected
// RUN: %diff -u %S/syntactic-rename/bar.expected %t.result/bar.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar_add_param.in.json %s >> %t.result/bar_add_param.expected
// RUN: %diff -u %S/syntactic-rename/bar_add_param.expected %t.result/bar_add_param.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar_drop_param.in.json %s >> %t.result/bar_drop_param.expected
// RUN: %diff -u %S/syntactic-rename/bar_drop_param.expected %t.result/bar_drop_param.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/comment.in.json %s >> %t.result/comment.expected
// RUN: %diff -u %S/syntactic-rename/comment.expected %t.result/comment.expected
// RUN: not %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/invalid.in.json %s
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/rename-memberwise.in.json %s >> %t.result/rename-memberwise.expected
// RUN: %diff -u %S/syntactic-rename/rename-memberwise.expected %t.result/rename-memberwise.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/rename-layer.in.json %s >> %t.result/rename-layer.expected
// RUN: %diff -u %S/syntactic-rename/rename-layer.expected %t.result/rename-layer.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/rename-P.in.json %s >> %t.result/rename-P.expected
// RUN: %diff -u %S/syntactic-rename/rename-P.expected %t.result/rename-P.expected
// RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/keywordbase.in.json %s >> %t.result/keywordbase.expected
// RUN: %diff -u %S/syntactic-rename/keywordbase.expected %t.result/keywordbase.expected
// RUN: %empty-directory(%t.ranges)
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/x.in.json %s >> %t.ranges/x.expected
// RUN: %diff -u %S/find-rename-ranges/x.expected %t.ranges/x.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/z.in.json %s >> %t.ranges/z.expected
// RUN: %diff -u %S/find-rename-ranges/z.expected %t.ranges/z.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/foo.in.json %s >> %t.ranges/foo_arity1.expected
// RUN: %diff -u %S/find-rename-ranges/foo_arity1.expected %t.ranges/foo_arity1.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/bar.in.json %s >> %t.ranges/bar.expected
// RUN: %diff -u %S/find-rename-ranges/bar.expected %t.ranges/bar.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/comment.in.json %s >> %t.ranges/comment.expected
// RUN: %diff -u %S/find-rename-ranges/comment.expected %t.ranges/comment.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/init.in.json %s >> %t.ranges/init.expected
// RUN: %diff -u %S/find-rename-ranges/init.expected %t.ranges/init.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/enum_case.in.json %s >> %t.result/enum_case.expected
// RUN: %diff -u %S/syntactic-rename/enum_case.expected %t.result/enum_case.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/rename-memberwise.in.json %s >> %t.ranges/rename-memberwise.expected
// RUN: %diff -u %S/find-rename-ranges/rename-memberwise.expected %t.ranges/rename-memberwise.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/rename-layer.in.json %s >> %t.ranges/rename-layer.expected
// RUN: %diff -u %S/find-rename-ranges/rename-layer.expected %t.ranges/rename-layer.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/rename-P.in.json %s -- -swift-version 4 >> %t.ranges/rename-P.expected
// RUN: %diff -u %S/find-rename-ranges/rename-P.expected %t.ranges/rename-P.expected
// RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/keywordbase.in.json %s -- -swift-version 4 >> %t.ranges/keywordbase.expected
// RUN: %diff -u %S/find-rename-ranges/keywordbase.expected %t.ranges/keywordbase.expected
| apache-2.0 |
jvesala/teknappi | teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift | 27 | 2165 | //
// Generate.swift
// Rx
//
// Created by Krunoslav Zaher on 9/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class GenerateSink<S, O: ObserverType> : Sink<O> {
typealias Parent = Generate<S, O.E>
let parent: Parent
var state: S
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
self.state = parent.initialState
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return parent.scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in
do {
if !isFirst {
self.state = try self.parent.iterate(self.state)
}
if try self.parent.condition(self.state) {
let result = try self.parent.resultSelector(self.state)
self.observer?.on(.Next(result))
recurse(false)
}
else {
self.observer?.on(.Completed)
self.dispose()
}
}
catch let error {
self.observer?.on(.Error(error))
self.dispose()
}
}
}
}
class Generate<S, E> : Producer<E> {
let initialState: S
let condition: S throws -> Bool
let iterate: S throws -> S
let resultSelector: S throws -> E
let scheduler: ImmediateSchedulerType
init(initialState: S, condition: S throws -> Bool, iterate: S throws -> S, resultSelector: S throws -> E, scheduler: ImmediateSchedulerType) {
self.initialState = initialState
self.condition = condition
self.iterate = iterate
self.resultSelector = resultSelector
self.scheduler = scheduler
super.init()
}
override func run<O : ObserverType where O.E == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = GenerateSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | gpl-3.0 |
Alecrim/AlecrimCoreData | Sources/Core/Persistent Container/CustomPersistentContainer.swift | 1 | 3233 | //
// CustomPersistentContainer.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 20/05/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
import CoreData
open class CustomPersistentContainer<Context: NSManagedObjectContext> {
// MARK: -
public private(set) lazy var backgroundContext: Context = self.newBackgroundContext()
// MARK: -
fileprivate let rawValue: NSPersistentContainer
// MARK: -
/// Use caution when using this initializer.
public init(name: String? = nil) {
self.rawValue = HelperPersistentContainer<Context>(name: name)
}
public init(name: String? = nil, managedObjectModel: NSManagedObjectModel, storageType: PersistentContainerStorageType, persistentStoreURL: URL, persistentStoreDescriptionOptions: [String : NSObject]? = nil, ubiquitousConfiguration: PersistentContainerUbiquitousConfiguration? = nil) throws {
self.rawValue = try HelperPersistentContainer<Context>(name: name, managedObjectModel: managedObjectModel, storageType: storageType, persistentStoreURL: persistentStoreURL, persistentStoreDescriptionOptions: persistentStoreDescriptionOptions, ubiquitousConfiguration: ubiquitousConfiguration)
}
public init(name: String, managedObjectModel: NSManagedObjectModel, persistentStoreDescription: NSPersistentStoreDescription, completionHandler: @escaping (NSPersistentContainer, NSPersistentStoreDescription, Error?) -> Void) throws {
self.rawValue = try HelperPersistentContainer<Context>(name: name, managedObjectModel: managedObjectModel, persistentStoreDescription: persistentStoreDescription, completionHandler: completionHandler)
}
// MARK: -
open var viewContext: Context {
return unsafeDowncast(self.rawValue.viewContext, to: Context.self)
}
open func newBackgroundContext() -> Context {
return unsafeDowncast(self.rawValue.newBackgroundContext(), to: Context.self)
}
open func performBackgroundTask(_ block: @escaping (Context) -> Void) {
self.rawValue.performBackgroundTask { managedObjectContext in
block(unsafeDowncast(managedObjectContext, to: Context.self))
}
}
}
// MARK: -
extension CustomPersistentContainer {
fileprivate final class HelperPersistentContainer<Context: NSManagedObjectContext>: PersistentContainer {
private lazy var _viewContext: NSManagedObjectContext = {
let context = Context(concurrencyType: .mainQueueConcurrencyType)
self.configureManagedObjectContext(context)
return context
}()
fileprivate override var viewContext: NSManagedObjectContext { return self._viewContext }
fileprivate override func newBackgroundContext() -> NSManagedObjectContext {
let context = Context(concurrencyType: .privateQueueConcurrencyType)
self.configureManagedObjectContext(context)
return context
}
fileprivate override func configureManagedObjectContext(_ context: NSManagedObjectContext) {
context.persistentStoreCoordinator = self.persistentStoreCoordinator
super.configureManagedObjectContext(context)
}
}
}
| mit |
loufranco/EventOMat | EventOMat/Views/UINavigationController+Extensions.swift | 1 | 488 | //
// UINavigationController+Extensions.swift
// EventOMat
//
// Created by Louis Franco on 2/17/17.
// Copyright © 2017 Lou Franco. All rights reserved.
//
import Foundation
import UIKit
// This extension makes the navigation controller use its top view controller to determine status bar style.
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return self.topViewController?.preferredStatusBarStyle ?? .default
}
}
| mit |
AnarchyTools/atbuild | tests/fixtures/configurations/src/main.swift | 1 | 229 | #if ATBUILD_DEBUG
print("Debug build")
#elseif ATBUILD_RELEASE
print("Release build")
#elseif ATBUILD_TEST
print("Test build")
#elseif ATBUILD_BENCH
print("Bench build")
#elseif ATBUILD_JAMES_BOND
print("James bond build")
#endif | apache-2.0 |
subdigital/cocoa-conf-boston-2014 | NetworkingDemo/NetworkingDemoTests/NetworkingDemoTests.swift | 1 | 924 | //
// NetworkingDemoTests.swift
// NetworkingDemoTests
//
// Created by Ben Scheirman on 11/8/14.
// Copyright (c) 2014 NSScreencast. All rights reserved.
//
import UIKit
import XCTest
class NetworkingDemoTests: 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 |
playstones/NEKit | src/Utils/Checksum.swift | 1 | 1569 | import Foundation
open class Checksum {
open static func computeChecksum(_ data: Data, from start: Int = 0, to end: Int? = nil, withPseudoHeaderChecksum initChecksum: UInt32 = 0) -> UInt16 {
return toChecksum(computeChecksumUnfold(data, from: start, to: end, withPseudoHeaderChecksum: initChecksum))
}
open static func validateChecksum(_ payload: Data, from start: Int = 0, to end: Int? = nil) -> Bool {
let cs = computeChecksumUnfold(payload, from: start, to: end)
return toChecksum(cs) == 0
}
open static func computeChecksumUnfold(_ data: Data, from start: Int = 0, to end: Int? = nil, withPseudoHeaderChecksum initChecksum: UInt32 = 0) -> UInt32 {
let scanner = BinaryDataScanner(data: data, littleEndian: true)
scanner.skip(to: start)
var result: UInt32 = initChecksum
var end = end
if end == nil {
end = data.count
}
while scanner.position + 2 <= end! {
let value = scanner.read16()!
result += UInt32(value)
}
if scanner.position != end {
// data is of odd size
// Intel and ARM are both litten endian
// so just add it
let value = scanner.readByte()!
result += UInt32(value)
}
return result
}
open static func toChecksum(_ checksum: UInt32) -> UInt16 {
var result = checksum
while (result) >> 16 != 0 {
result = result >> 16 + result & 0xFFFF
}
return ~UInt16(result)
}
}
| bsd-3-clause |
vinsan/presteasymo | presteasymo/presteasymoUITests/presteasymoUITests.swift | 1 | 1261 | //
// presteasymoUITests.swift
// presteasymoUITests
//
// Created by Vincenzo Santoro on 03/04/2017.
// Copyright © 2017 Team 2.4. All rights reserved.
//
import XCTest
class presteasymoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| apache-2.0 |
zhiquan911/chance_btc_wallet | chance_btc_wallet/chance_btc_wallet/viewcontrollers/setting/SettingViewController.swift | 1 | 9443 | //
// SettingViewController.swift
// Chance_wallet
//
// Created by Chance on 16/1/26.
// Copyright © 2016年 Chance. All rights reserved.
//
import UIKit
class SettingViewController: BaseTableViewController {
/// 列表title
var rowsTitle: [[String]] = [
[
"Export Public Key".localized(),
"Export Private Key".localized(),
"Export RedeemScript".localized(),
],
[
"Export Wallet Passphrases".localized(),
"Restore Wallet By Passphrases".localized(),
],
[
"Security Setting".localized(),
],
[
"Blockchain Nodes".localized(),
],
[
"iCloud Auto Backup".localized(),
],
[
"Reset Wallet".localized(),
]
]
var currentAccount: CHBTCAcount? {
let i = CHBTCWallet.sharedInstance.selectedAccountIndex
if i != -1 {
return CHBTCWallet.sharedInstance.getAccount(byIndex: i)
} else {
return nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//CloudUtils.shared.query()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.rowsTitle.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
if let account = self.currentAccount {
if account.accountType == .multiSig {
return self.rowsTitle[section].count
} else {
return self.rowsTitle[section].count - 1
}
} else {
return 0
}
default:
return self.rowsTitle[section].count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SettingCell.cellIdentifier) as! SettingCell
cell.switchEnable.isHidden = true
cell.accessoryType = .disclosureIndicator
cell.labelTitle.text = self.rowsTitle[indexPath.section][indexPath.row]
switch indexPath.section {
case 4: //icloud同步开关
cell.accessoryType = .none
cell.switchEnable.isHidden = false
cell.switchEnable.isOn = CHWalletWrapper.enableICloud
//设置是否登录icloud账号
if CloudUtils.shared.iCloud {
cell.switchEnable.isEnabled = true
} else {
cell.switchEnable.isEnabled = false
}
//开关调用
cell.enableChange = {
(pressCell, sender) -> Void in
self.handleICloudBackupChange(sender: sender)
}
default:
cell.switchEnable.isHidden = true
cell.accessoryType = .disclosureIndicator
}
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 18
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == self.numberOfSections(in: self.tableView) - 1 {
return 60
} else {
return 0.01
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let doBlock = {
() -> Void in
var title = ""
if indexPath.section == 0 {
var keyType = ExportKeyType.PublicKey
if indexPath.row == 0 {
keyType = ExportKeyType.PublicKey
title = "Public Key".localized()
} else if indexPath.row == 1 {
keyType = ExportKeyType.PrivateKey
title = "Private Key".localized()
} else if indexPath.row == 2 {
keyType = ExportKeyType.RedeemScript
title = "RedeemScript".localized()
}
guard let vc = StoryBoard.setting.initView(type: ExportKeyViewController.self) else {
return
}
vc.currentAccount = self.currentAccount!
vc.keyType = keyType
vc.navigationItem.title = title
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 1 {
var restoreOperateType = RestoreOperateType.lookupPassphrase
var title = ""
if indexPath.row == 0 {
restoreOperateType = .lookupPassphrase
title = "Passphrase".localized()
} else {
restoreOperateType = .initiativeRestore
title = "Restore wallet".localized()
}
guard let vc = StoryBoard.setting.initView(type: RestoreWalletViewController.self) else {
return
}
vc.restoreOperateType = restoreOperateType
vc.navigationItem.title = title
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 2 {
if indexPath.row == 0 {
guard let vc = StoryBoard.setting.initView(type: PasswordSettingViewController.self) else {
return
}
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
} else if indexPath.section == 3 {
//进入设置云节点
if indexPath.row == 0 {
guard let vc = StoryBoard.setting.initView(type: BlockchainNodeSettingViewController.self) else {
return
}
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
} else if indexPath.section == 4 {
} else if indexPath.section == 5 {
self.showResetWalletAlert()
}
}
switch indexPath.section {
case 0, 1, 2, 5: //需要密码
//需要提供指纹密码
CHWalletWrapper.unlock(vc: self, complete: {
(flag, error) in
if flag {
doBlock()
} else {
if error != "" {
SVProgressHUD.showError(withStatus: error)
}
}
})
default: //默认不需要密码
doBlock()
}
}
}
// MARK: - 控制器方法
extension SettingViewController {
/**
配置UI
*/
func setupUI() {
self.navigationItem.title = "Setting".localized()
}
/// 切换是否使用icloud备份
///
/// - Parameter sender:
@IBAction func handleICloudBackupChange(sender: UISwitch) {
CHWalletWrapper.enableICloud = sender.isOn
if sender.isOn {
//开启后,马上进行同步
let db = RealmDBHelper.shared.acountDB
RealmDBHelper.shared.iCloudSynchronize(db: db)
}
}
/// 弹出重置钱包的警告
func showResetWalletAlert() {
let actionSheet = UIAlertController(title: "Warning".localized(), message: "Please backup your passphrase before you do that.It's dangerous.".localized(), preferredStyle: UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Reset".localized(), style: UIAlertActionStyle.default, handler: {
(action) -> Void in
//删除钱包所有资料
CHWalletWrapper.deleteAllWallets()
//弹出欢迎界面,创新创建钱包
AppDelegate.sharedInstance().restoreWelcomeController()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel, handler: {
(action) -> Void in
}))
self.present(actionSheet, animated: true, completion: nil)
}
}
| mit |
natecook1000/swift | test/SILGen/objc_factory_init.swift | 3 | 6617 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serializable] [thunk] @$SSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : @owned $Optional<Bee>, [[HIVE_META:%[0-9]+]] : @trivial $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: destroy_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory initializer,
// not a convenience initializer, which means it does not have an initializing
// entry point at all.
// CHECK-LABEL: sil hidden @$SSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive {
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[OLD_HIVE:%.*]] : @owned $Hive):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var Hive }, 0
// CHECK: store [[OLD_HIVE]] to [init] [[PB_BOX]]
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]]
// CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[BORROWED_SELF]] : $Hive
// CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]]
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[BORROWED_QUEEN:%.*]] = begin_borrow [[QUEEN]]
// CHECK: [[COPIED_BORROWED_QUEEN:%.*]] = copy_value [[BORROWED_QUEEN]]
// CHECK: [[OPT_COPIED_BORROWED_QUEEN:%.*]] = enum $Optional<Bee>, #Optional.some!enumelt.1, [[COPIED_BORROWED_QUEEN]]
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: [[NEW_HIVE:%.*]] = apply [[FACTORY]]([[OPT_COPIED_BORROWED_QUEEN]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[OPT_COPIED_BORROWED_QUEEN]]
// CHECK: end_borrow [[BORROWED_QUEEN]] from [[QUEEN]]
// CHECK: switch_enum [[NEW_HIVE]] : $Optional<Hive>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[NEW_HIVE:%.*]] : @owned $Hive):
// CHECK: assign [[NEW_HIVE]] to [[PB_BOX]]
// CHECK: } // end sil function '$SSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc'
convenience init(otherQueen other: Bee) {
self.init(queen: other)
}
// CHECK-LABEL: sil hidden @$SSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC : $@convention(method) (@owned Bee, @thick Hive.Type) -> (@owned Hive, @error Error) {
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[METATYPE:%.*]] : @trivial $@thick Hive.Type):
// CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]]
// CHECK: [[HIVE:%.*]] = alloc_ref_dynamic [objc] [[OBJC_METATYPE]]
// CHECK: try_apply {{.*}}([[QUEEN]], [[HIVE]]) : $@convention(method) (@owned Bee, @owned Hive) -> (@owned Hive, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
//
// CHECK: [[NORMAL_BB]]([[HIVE:%.*]] : @owned $Hive):
// CHECK: return [[HIVE]]
//
// CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
// CHECK: builtin "willThrow"([[ERROR]] : $Error)
// CHECK: throw [[ERROR]]
// CHECK: } // end sil function '$SSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC'
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// CHECK-LABEL: sil hidden @$SSo12IAMSomeClassC17objc_factory_initE6doubleABSd_tcfc : $@convention(method) (Double, @owned SomeClass) -> @owned SomeClass {
// CHECK: bb0([[DOUBLE:%.*]] : @trivial $Double,
// CHECK-NOT: value_metatype
// CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// CHECK: apply [[FNREF]]([[DOUBLE]])
// CHECK: } // end sil function '$SSo12IAMSomeClassC17objc_factory_initE6doubleABSd_tcfc'
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden @$S17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive {
// CHECK: bb0([[SUBHIVE:%.*]] : @owned $SubHive):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SubHive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var SubHive }
// CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var SubHive }, 0
// CHECK: store [[SUBHIVE]] to [init] [[PB_BOX]]
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]]
// CHECK: [[UPCAST_BORROWED_SELF:%.*]] = upcast [[BORROWED_SELF]] : $SubHive to $Hive
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST_BORROWED_SELF:%.*]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]]
// CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]]
// CHECK: [[QUEEN:%.*]] = unchecked_ref_cast {{.*}} : $Bee to $Optional<Bee>
// CHECK: [[HIVE_INIT_FN:%.*]] = objc_method [[OBJC_METATYPE]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign
// CHECK: apply [[HIVE_INIT_FN]]([[QUEEN]], [[OBJC_METATYPE]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[QUEEN]]
// CHECK: } // end sil function '$S17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc'
convenience init(delegatesToInherited: ()) {
self.init(queen: Bee())
}
}
| apache-2.0 |
endoze/Initializable | InitializableTests/ConfigurableSpec.swift | 1 | 1063 | //
// ConfigurableSpec.swift
// Initializable
//
// Created by Endoze on 4/21/16.
// Copyright © 2016 Wide Eye Labs. All rights reserved.
//
import Quick
import Nimble
import Initializable
class ConfigurableSpec: QuickSpec {
override func spec() {
describe("Configurable") {
describe("currentStage") {
it("returns a ReleaseStage") {
let configuration = Configuration.defaultConfiguration()
expect(configuration.currentStage()).to(equal(ReleaseStage.development))
}
}
describe("serviceStorage") {
let configuration = Configuration.defaultConfiguration()
context("when a value exists for a service") {
it("returns a key") {
expect(configuration.value(for: "FakeService", key: "ApiKey")).to(equal("abc123"))
}
}
context("when a value doesn't exist for a service") {
it("returns nil") {
expect(configuration.value(for: "FakeService", key: "DoesNotExist")).to(beNil())
}
}
}
}
}
}
| mit |
dduan/swift | validation-test/compiler_crashers_fixed/00179-swift-protocolcompositiontype-build.swift | 11 | 2506 | // 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
// RUN: not %target-swift-frontend %s -parse
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h A {
func c() -> String
}
class B {
func d() -> String {
return ""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
d
}
protocol t {
}
protocol d : t {
}
protocol g : t {
}
s
q l
})
}
d(t(u, t(w, y)))
protocol e {
r j
}
struct m<v : e> {
k x: v
k x: v.j
}
protocol n for (mx : e?) in c {
}
}
struct A<T> {
let a: [(T, () -> ())] = []
}
)
func o<t>() -> (t, t -> t) -> t {
j j j.o = {
}
{
t) {
h }
}
protocol o {
class func o()
}
class j: o{ class func o {}
e o<j : u> {
k []
}
n=p r n=p
func n<q>() {
b b {
o o
}
}
func n(j: Any, t: Any) -> (((Any, Any) -> Any) -> Any) {
k {
(s: (Any, Any) -> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o : A {
func b(b: X.Type) {
}
}
f> {
c(d ())
}
func b(e)-> <d>(() -> d)
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
func b<e>(e : e) -> c { e
func m<u>() -> (u, u - w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
class A: A {
}
class B : C {
}
typealias C = B
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
d)
func e(h: b) -> <f>(() -> f) -> b {
return { c):h())" }
}
class f<d : d, j : d k d.l == j> {
}
protocol d {
i l
i i
}
struct l<l : d> : d {
i j i() {
l.i()
}
}
protocol f {
}
protocol d : f {
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func c<e>() -> (e -> e) -> e {
e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> == q.n> {
}
o l {
u n
}
y q) -> ())
}
o n ())
}
| apache-2.0 |
jekahy/Grocr | Grocr/Protocols/ErrorBorder.swift | 1 | 425 | //
// ErrorBorder.swift
// The app
//
// Created by Eugene on 26.05.17.
// Copyright © 2017 Eugenious. All rights reserved.
//
import Foundation
import UIKit
protocol ErrorBorder {}
extension ErrorBorder where Self:UIView{
func highlightError()
{
self.layer.borderColor = UIColor.red.cgColor
self.layer.borderWidth = 2.0
}
func removeErrorHighlight()
{
self.layer.borderWidth = 0
}
}
| mit |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Reference/google/protobuf/duration.pb.swift | 1 | 7085 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/duration.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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
// OWNER 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 Foundation
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// A Duration represents a signed, fixed-length span of time represented
/// as a count of seconds and fractions of seconds at nanosecond
/// resolution. It is independent of any calendar and concepts like "day"
/// or "month". It is related to Timestamp in that the difference between
/// two Timestamp values is a Duration and it can be added or subtracted
/// from a Timestamp. Range is approximately +-10,000 years.
///
/// # Examples
///
/// Example 1: Compute Duration from two Timestamps in pseudo code.
///
/// Timestamp start = ...;
/// Timestamp end = ...;
/// Duration duration = ...;
///
/// duration.seconds = end.seconds - start.seconds;
/// duration.nanos = end.nanos - start.nanos;
///
/// if (duration.seconds < 0 && duration.nanos > 0) {
/// duration.seconds += 1;
/// duration.nanos -= 1000000000;
/// } else if (durations.seconds > 0 && duration.nanos < 0) {
/// duration.seconds -= 1;
/// duration.nanos += 1000000000;
/// }
///
/// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
///
/// Timestamp start = ...;
/// Duration duration = ...;
/// Timestamp end = ...;
///
/// end.seconds = start.seconds + duration.seconds;
/// end.nanos = start.nanos + duration.nanos;
///
/// if (end.nanos < 0) {
/// end.seconds -= 1;
/// end.nanos += 1000000000;
/// } else if (end.nanos >= 1000000000) {
/// end.seconds += 1;
/// end.nanos -= 1000000000;
/// }
///
/// Example 3: Compute Duration from datetime.timedelta in Python.
///
/// td = datetime.timedelta(days=3, minutes=10)
/// duration = Duration()
/// duration.FromTimedelta(td)
///
/// # JSON Mapping
///
/// In JSON format, the Duration type is encoded as a string rather than an
/// object, where the string ends in the suffix "s" (indicating seconds) and
/// is preceded by the number of seconds, with nanoseconds expressed as
/// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
/// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
/// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
/// microsecond should be expressed in JSON format as "3.000001s".
struct Google_Protobuf_Duration {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Signed seconds of the span of time. Must be from -315,576,000,000
/// to +315,576,000,000 inclusive. Note: these bounds are computed from:
/// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
var seconds: Int64 = 0
/// Signed fractions of a second at nanosecond resolution of the span
/// of time. Durations less than one second are represented with a 0
/// `seconds` field and a positive or negative `nanos` field. For durations
/// of one second or more, a non-zero value for the `nanos` field must be
/// of the same sign as the `seconds` field. Must be from -999,999,999
/// to +999,999,999 inclusive.
var nanos: Int32 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "google.protobuf"
extension Google_Protobuf_Duration: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Duration"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "seconds"),
2: .same(proto: "nanos"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt64Field(value: &self.seconds)
case 2: try decoder.decodeSingularInt32Field(value: &self.nanos)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.seconds != 0 {
try visitor.visitSingularInt64Field(value: self.seconds, fieldNumber: 1)
}
if self.nanos != 0 {
try visitor.visitSingularInt32Field(value: self.nanos, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: Google_Protobuf_Duration) -> Bool {
if self.seconds != other.seconds {return false}
if self.nanos != other.nanos {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
| gpl-3.0 |
wuhduhren/Mr-Ride-iOS | Mr-Ride-iOS/Model/CalorieCalculator.swift | 1 | 722 | //
// CalorieCalculator.swift
// Mr-Ride
//
// Created by howard hsien on 2016/5/30.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import Foundation
class CalorieCalculator {
private var kCalPerKm_Hour : Dictionary <Exercise,Double> = [
.Bike : 0.4
]
enum Exercise {
case Bike
}
// unit
// speed : km/h
// weight: kg
// time: hr
// return : kcal
func kiloCalorieBurned(exerciseType: Exercise, speed: Double, weight: Double, time:Double) -> Double{
if let kCalUnit = kCalPerKm_Hour[exerciseType]{
return speed * weight * time * kCalUnit
}
else{
return 0.0
}
}
} | mit |
envoyproxy/envoy | mobile/library/swift/ResponseHeadersBuilder.swift | 2 | 844 | import Foundation
/// Builder used for constructing instances of `ResponseHeaders`.
@objcMembers
public final class ResponseHeadersBuilder: HeadersBuilder {
/// Initialize a new instance of the builder.
public override convenience init() {
self.init(container: HeadersContainer(headers: [:]))
}
/// Add an HTTP status to the response headers.
///
/// - parameter status: The HTTP status to add.
///
/// - returns: This builder.
@discardableResult
public func addHttpStatus(_ status: UInt) -> ResponseHeadersBuilder {
self.internalSet(name: ":status", value: ["\(status)"])
return self
}
/// Build the response headers using the current builder.
///
/// - returns: New instance of response headers.
public func build() -> ResponseHeaders {
return ResponseHeaders(container: self.container)
}
}
| apache-2.0 |
runtastic/Matrioska | Source/Components/StackCluster.swift | 1 | 4847 | //
// StackCluster.swift
// Matrioska
//
// Created by Alex Manzella on 16/11/16.
// Copyright © 2016 runtastic. All rights reserved.
//
import Foundation
extension ClusterLayout {
/// Stack component configuration.
public struct StackConfig: ExpressibleByComponentMeta {
/// The title of the stack view, nil by default.
public let title: String?
/// The spacing of the components inside the stack. Default 10.
public let spacing: CGFloat
/// The axis of the stack view, by default is vertical.
/// A stack with a horizontal axis is a row of arrangedSubviews,
/// and a stack with a vertical axis is a column of arrangedSubviews.
public let axis: UILayoutConstraintAxis
/// Defines if the arranged subviews should preserve the parent width
/// or their own intrinsicContentSize. Default false.
public let preserveParentWidth: Bool
/// The backgroundColor of the stackView, Default is white.
public let backgroundColor: UIColor
/// Initialize a stack configuration from a `ComponentMeta`
/// Used to materialzie `StackConfig` if the meta contains the values needed.
/// The default values will be used where `meta` doesn't have a valid ones.
///
/// - Parameter meta: A meta object
public init?(meta: ComponentMeta) {
let title = meta["title"] as? String
let spacing = (meta["spacing"] as? NSNumber)?.floatValue
let preserveParentWidth = meta["preserve_parent_width"] as? Bool
var axis = UILayoutConstraintAxis.vertical
if let orientationRawValue = meta["orientation"] as? String,
let orientation = Orientation(rawValue: orientationRawValue) {
axis = orientation.layoutConstraintAxis
}
let hexString = meta["background_color"] as? String
let backgroundColor = hexString.flatMap { UIColor(hexString: $0) }
self.init(
title: title,
spacing: spacing.map { CGFloat($0) },
axis: axis,
preserveParentWidth: preserveParentWidth,
backgroundColor: backgroundColor
)
}
/// Creates a new stack configuration
///
/// - Parameters:
/// - title: The title of the stack view, nil by default.
/// - spacing: The spacing of the components inside the stack. Default 10.
/// - axis: The axis of the stack view, by default is vertical.
/// - preserveParentWidth: Defines the arranged subviews should preserve the parent width
/// or their own intrinsicContentSize. Default false.
/// - backgroundColor: The backgroundColor of the stackView, Default is white.
public init(title: String? = nil,
spacing: CGFloat? = nil,
axis: UILayoutConstraintAxis? = nil,
preserveParentWidth: Bool? = nil,
backgroundColor: UIColor? = nil) {
self.title = title
self.spacing = spacing ?? 10
self.axis = axis ?? .vertical
self.preserveParentWidth = preserveParentWidth ?? false
self.backgroundColor = backgroundColor ?? .white
}
}
/// A stack cluster component.
/// It arranges its children views in a vertical or horizontal stack, configured with the meta.
///
/// - Parameters:
/// - children: The children components
/// - meta: Should represent `StackConfig` object to configure the stack view
/// - Returns: A stack component
public static func stack(children: [Component], meta: ComponentMeta?) -> Component {
return Component.cluster(viewBuilder: stackBuilder,
children: children,
meta: meta)
}
private static func stackBuilder(_ children: [Component],
_ meta: ComponentMeta?) -> UIViewController? {
let stackViewController = StackViewController(configuration: StackConfig.materialize(meta))
stackViewController.add(children: children)
return stackViewController
}
}
fileprivate enum Orientation: String {
case horizontal
case vertical
var layoutConstraintAxis: UILayoutConstraintAxis {
switch self {
case .horizontal: return .horizontal
case .vertical: return .vertical
}
}
}
fileprivate extension StackViewController {
func add(children: [Component]) {
for child in children {
guard let viewController = child.viewController() else {
continue
}
add(child: viewController)
}
}
}
| mit |
Arcovv/CleanArchitectureRxSwift | RealmPlatform/Entities/RMAddress.swift | 1 | 1458 | //
// RMAddress.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import QueryKit
import Domain
import RealmSwift
import Realm
final class RMAddress: Object {
dynamic var city: String = ""
dynamic var geo: RMLocation?
dynamic var street: String = ""
dynamic var suite: String = ""
dynamic var zipcode: String = ""
}
extension RMAddress {
static var city: Attribute<String> { return Attribute("city")}
static var street: Attribute<String> { return Attribute("street")}
static var suite: Attribute<String> { return Attribute("suite")}
static var zipcode: Attribute<String> { return Attribute("zipcode")}
static var geo: Attribute<RMLocation> { return Attribute("geo")}
}
extension RMAddress: DomainConvertibleType {
func asDomain() -> Address {
return Address(city: city,
geo: geo!.asDomain(),
street: street,
suite: suite,
zipcode: zipcode)
}
}
extension Address: RealmRepresentable {
internal var uid: String {
return ""
}
func asRealm() -> RMAddress {
return RMAddress.build { object in
object.city = city
object.geo = geo.asRealm()
object.street = street
object.suite = suite
object.zipcode = zipcode
}
}
}
| mit |
pietu/SImperial | SImperial/PopOverViewController.swift | 1 | 1475 | //
// PopOverViewController.swift
// SImperial
//
// Created by Petteri Parkkila on 05/12/16.
// Copyright © 2016 Pietu. All rights reserved.
//
import UIKit
class PopOverViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var isFromUnit: Bool = false
var compelition: ((_ unit: Dictionary<String,Dimension>) -> Void)? = nil
var unitSelections: [Dictionary<String,Dimension>]? = nil
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let selections = self.unitSelections {
return selections.count
} else {
return 0
}
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "unitCell")
cell.textLabel?.font = UIFont(name: "Montserrat-Regular", size: 17)
if let selections = self.unitSelections {
if let name = selections[indexPath.row].keys.first {
cell.textLabel?.text = name + ", " + (selections[indexPath.row][name]?.symbol)!
}
} else {
cell.textLabel?.text = "No content available"
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let selections = self.unitSelections {
if let cb = compelition {
cb(selections[indexPath.row])
}
}
self.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 |
changjianfeishui/iOS_Tutorials_Of_Swift | Custom View Controller Transitions/iLoveCatz/iLoveCatz/SwipeInteractionController.swift | 1 | 2081 | //
// SwipeInteractionController.swift
// iLoveCatz
//
// Created by XB on 16/5/17.
// Copyright © 2016年 XB. All rights reserved.
//
import UIKit
class SwipeInteractionController: UIPercentDrivenInteractiveTransition {
var interactionInProgress:Bool = false
private var _shouldCompleteTransition:Bool = false
private var _navigationController:UINavigationController!
//This method allows you to attach the interaction controller to a view controller.
func wireToViewController(viewController:UIViewController) {
_navigationController = viewController.navigationController!
self.prepareGestureRecognizerInView(viewController.view)
}
//This method adds a gesture recognizer to the view controller’s view to detect a pan.
func prepareGestureRecognizerInView(view:UIView) {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
view.addGestureRecognizer(gesture)
}
func handlePan(pan:UIPanGestureRecognizer) -> Void {
let translation = pan.translationInView(pan.view?.superview)
switch pan.state {
case .Began:
// 1. Start an interactive transition!
self.interactionInProgress = true
_navigationController.popViewControllerAnimated(true)
case .Changed:
// 2. compute the current position
var fraction = -(translation.x / 200.0)
fraction = CGFloat(fminf(fmaxf(Float(fraction), 0.0), 1.0))
// 3. should we complete?
_shouldCompleteTransition = (fraction > 0.5)
// 4. update the animation
self.updateInteractiveTransition(fraction)
case .Ended,.Cancelled:
self.interactionInProgress = false
if !_shouldCompleteTransition||pan.state == UIGestureRecognizerState.Cancelled {
self.cancelInteractiveTransition()
}else{
self.finishInteractiveTransition()
}
default:
break
}
}
}
| mit |
BenjyAir/Sunshine | Summer/SummerTests/SummerTests.swift | 1 | 953 | //
// SummerTests.swift
// SummerTests
//
// Created by Benjy on 12/2/16.
// Copyright © 2016 Benjy. All rights reserved.
//
import XCTest
@testable import Summer
class SummerTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
benlangmuir/swift | test/SILGen/address_only_types.swift | 2 | 9718 |
// RUN: %target-swift-emit-silgen -module-name address_only_types -parse-as-library -parse-stdlib %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F
func address_only_argument(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable):
// CHECK: debug_value [[XARG]] {{.*}} expr op_deref
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable):
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F
func address_only_return(_ x: Unloadable, y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable, [[XARG:%[0-9]+]] : $*any Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64):
// CHECK-NEXT: debug_value [[XARG]] : $*any Unloadable, let, name "x", {{.*}} expr op_deref
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*any Unloadable, {{%.*}} : $*any Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr %1 to [initialization] %0 : $*any Unloadable
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B29_conditional_missing_return_2
func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*any Unloadable, {{%.*}} : $*any Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(_ x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_call_1
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B21_call_1_ignore_returnyyF
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F
func address_only_call_2(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable):
// CHECK: debug_value [[XARG]] : $*any Unloadable, {{.*}} expr op_deref
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]([[XARG]])
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*any Unloadable to $*[[OPENED:@opened\(.*, any Unloadable\) Self]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo :
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp(_ dest: inout Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : $*any Unloadable):
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: %[[ACCESS:.*]] = begin_access [modify] [unknown] %0 :
// CHECK: copy_addr [take] [[TEMP]] to %[[ACCESS]] :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : $*any Unloadable, [[VARG:%[0-9]+]] : $*any Unloadable):
// CHECK: [[VBOX:%.*]] = alloc_box ${ var any Unloadable }
// CHECK: [[V_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[VBOX]]
// CHECK: [[PBOX:%[0-9]+]] = project_box [[V_LIFETIME]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*any Unloadable
dest = v
// CHECK: [[READBOX:%.*]] = begin_access [read] [unknown] [[PBOX]] :
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: copy_addr [[READBOX]] to [initialization] [[TEMP]] :
// CHECK: [[RET:%.*]] = begin_access [modify] [unknown] %0 :
// CHECK: copy_addr [take] [[TEMP]] to [[RET]] :
// CHECK: destroy_value [[VBOX]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @$s18address_only_types11global_propAA10Unloadable_pvs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv_to_property(_ v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : $*any Unloadable):
// CHECK: debug_value [[VARG]] : $*any Unloadable, {{.*}} expr op_deref
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @$s18address_only_types11global_propAA10Unloadable_pvs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B4_varAA10Unloadable_pyF
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var any Unloadable }
// CHECK: [[XBOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[XPB:%.*]] = project_box [[XBOX_LIFETIME]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XPB]] :
// CHECK: copy_addr [[ACCESS]] to [initialization] %0
// CHECK: destroy_value [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden [ossa] @$s18address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F
func call_address_only_nontuple_arg_function(_ x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
| apache-2.0 |
benlangmuir/swift | stdlib/public/core/StringUTF8Validation.swift | 30 | 8056 | private func _isUTF8MultiByteLeading(_ x: UInt8) -> Bool {
return (0xC2...0xF4).contains(x)
}
private func _isNotOverlong_F0(_ x: UInt8) -> Bool {
return (0x90...0xBF).contains(x)
}
private func _isNotOverlong_F4(_ x: UInt8) -> Bool {
return UTF8.isContinuation(x) && x <= 0x8F
}
private func _isNotOverlong_E0(_ x: UInt8) -> Bool {
return (0xA0...0xBF).contains(x)
}
private func _isNotOverlong_ED(_ x: UInt8) -> Bool {
return UTF8.isContinuation(x) && x <= 0x9F
}
internal struct UTF8ExtraInfo: Equatable {
public var isASCII: Bool
}
internal enum UTF8ValidationResult {
case success(UTF8ExtraInfo)
case error(toBeReplaced: Range<Int>)
}
extension UTF8ValidationResult: Equatable {}
private struct UTF8ValidationError: Error {}
internal func validateUTF8(_ buf: UnsafeBufferPointer<UInt8>) -> UTF8ValidationResult {
if _allASCII(buf) {
return .success(UTF8ExtraInfo(isASCII: true))
}
var iter = buf.makeIterator()
var lastValidIndex = buf.startIndex
@inline(__always) func guaranteeIn(_ f: (UInt8) -> Bool) throws {
guard let cu = iter.next() else { throw UTF8ValidationError() }
guard f(cu) else { throw UTF8ValidationError() }
}
@inline(__always) func guaranteeContinuation() throws {
try guaranteeIn(UTF8.isContinuation)
}
func _legacyInvalidLengthCalculation(_ _buffer: (_storage: UInt32, ())) -> Int {
// function body copied from UTF8.ForwardParser._invalidLength
if _buffer._storage & 0b0__1100_0000__1111_0000
== 0b0__1000_0000__1110_0000 {
// 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result
// must be nonzero and not a surrogate
let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111
if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 }
}
else if _buffer._storage & 0b0__1100_0000__1111_1000
== 0b0__1000_0000__1111_0000
{
// Prefix of 4-byte sequence. The top 5 bits of the decoded result
// must be nonzero and no greater than 0b0__0100_0000
let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111)
if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 {
return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000
== 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2
}
}
return 1
}
func _legacyNarrowIllegalRange(buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> {
var reversePacked: UInt32 = 0
if let third = buf.dropFirst(2).first {
reversePacked |= UInt32(third)
reversePacked <<= 8
}
if let second = buf.dropFirst().first {
reversePacked |= UInt32(second)
reversePacked <<= 8
}
reversePacked |= UInt32(buf.first!)
let _buffer: (_storage: UInt32, x: ()) = (reversePacked, ())
let invalids = _legacyInvalidLengthCalculation(_buffer)
return buf.startIndex ..< buf.startIndex + invalids
}
func findInvalidRange(_ buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> {
var endIndex = buf.startIndex
var iter = buf.makeIterator()
_ = iter.next()
while let cu = iter.next(), UTF8.isContinuation(cu) {
endIndex += 1
}
let illegalRange = Range(buf.startIndex...endIndex)
_internalInvariant(illegalRange.clamped(to: (buf.startIndex..<buf.endIndex)) == illegalRange,
"illegal range out of full range")
// FIXME: Remove the call to `_legacyNarrowIllegalRange` and return `illegalRange` directly
return _legacyNarrowIllegalRange(buf: buf[illegalRange])
}
do {
var isASCII = true
while let cu = iter.next() {
if UTF8.isASCII(cu) { lastValidIndex &+= 1; continue }
isASCII = false
if _slowPath(!_isUTF8MultiByteLeading(cu)) {
throw UTF8ValidationError()
}
switch cu {
case 0xC2...0xDF:
try guaranteeContinuation()
lastValidIndex &+= 2
case 0xE0:
try guaranteeIn(_isNotOverlong_E0)
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xE1...0xEC:
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xED:
try guaranteeIn(_isNotOverlong_ED)
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xEE...0xEF:
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xF0:
try guaranteeIn(_isNotOverlong_F0)
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
case 0xF1...0xF3:
try guaranteeContinuation()
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
case 0xF4:
try guaranteeIn(_isNotOverlong_F4)
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
default:
Builtin.unreachable()
}
}
return .success(UTF8ExtraInfo(isASCII: isASCII))
} catch {
return .error(toBeReplaced: findInvalidRange(buf[lastValidIndex...]))
}
}
internal func repairUTF8(_ input: UnsafeBufferPointer<UInt8>, firstKnownBrokenRange: Range<Int>) -> String {
_internalInvariant(!input.isEmpty, "empty input doesn't need to be repaired")
_internalInvariant(firstKnownBrokenRange.clamped(to: input.indices) == firstKnownBrokenRange)
// During this process, `remainingInput` contains the remaining bytes to process. It's split into three
// non-overlapping sub-regions:
//
// 1. `goodChunk` (may be empty) containing bytes that are known good UTF-8 and can be copied into the output String
// 2. `brokenRange` (never empty) the next range of broken bytes,
// 3. the remainder (implicit, will become the next `remainingInput`)
//
// At the beginning of the process, the `goodChunk` starts at the beginning and extends to just before the first
// known broken byte. The known broken bytes are covered in the `brokenRange` and everything following that is
// the remainder.
// We then copy the `goodChunk` into the target buffer and append a UTF8 replacement character. `brokenRange` is
// skipped (replaced by the replacement character) and we restart the same process. This time, `goodChunk` extends
// from the byte after the previous `brokenRange` to the next `brokenRange`.
var result = _StringGuts()
let replacementCharacterCount = Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { $0.count }
result.reserveCapacity(input.count + 5 * replacementCharacterCount) // extra space for some replacement characters
var brokenRange: Range<Int> = firstKnownBrokenRange
var remainingInput = input
repeat {
_internalInvariant(!brokenRange.isEmpty, "broken range empty")
_internalInvariant(!remainingInput.isEmpty, "empty remaining input doesn't need to be repaired")
let goodChunk = remainingInput[..<brokenRange.startIndex]
// very likely this capacity reservation does not actually do anything because we reserved space for the entire
// input plus up to five replacement characters up front
result.reserveCapacity(result.count + remainingInput.count + replacementCharacterCount)
// we can now safely append the next known good bytes and a replacement character
result.appendInPlace(UnsafeBufferPointer(rebasing: goodChunk),
isASCII: false /* appending replacement character anyway, so let's not bother */)
Unicode.Scalar._replacementCharacter.withUTF8CodeUnits {
result.appendInPlace($0, isASCII: false)
}
remainingInput = UnsafeBufferPointer(rebasing: remainingInput[brokenRange.endIndex...])
switch validateUTF8(remainingInput) {
case .success:
result.appendInPlace(remainingInput, isASCII: false)
return String(result)
case .error(let newBrokenRange):
brokenRange = newBrokenRange
}
} while !remainingInput.isEmpty
return String(result)
}
| apache-2.0 |
bitjammer/swift | validation-test/compiler_crashers_fixed/27299-swift-enumtype-get.swift | 65 | 436 | // 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
{a:{struct c<T:T.h}}class e{var d= <l
| apache-2.0 |
malaonline/iOS | mala-ios/Model/Course/TeacherModel.swift | 1 | 2233 | //
// TeacherModel.swift
// mala-ios
//
// Created by Erdi on 12/23/15.
// Copyright © 2015 Mala Online. All rights reserved.
//
import UIKit
class TeacherModel: BaseObjectModel {
// MARK: - Property
var avatar: String?
var gender: String?
var level: Int = 0
var min_price: Int = 0
var max_price: Int = 0
var subject: String?
var grades_shortname: String?
var tags: [String]?
// MARK: - Constructed
override init() {
super.init()
}
override init(dict: [String: Any]) {
super.init(dict: dict)
setValuesForKeys(dict)
}
convenience init(id: Int, name: String, avatar: String, degree: Int, minPrice: Int, maxPrice: Int, subject: String, shortname: String, tags: [String]) {
self.init()
self.id = id
self.name = name
self.avatar = avatar
self.level = degree
self.min_price = minPrice
self.max_price = maxPrice
self.subject = subject
self.grades_shortname = shortname
self.tags = tags
}
convenience init(id: Int, name: String, avatar: String) {
self.init()
self.id = id
self.name = name
self.avatar = avatar
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Override
override func setValue(_ value: Any?, forUndefinedKey key: String) {
println("TeacherModel - Set for UndefinedKey: \(key)")
}
override func setValue(_ value: Any?, forKey key: String) {
// keep the price's value to 0(Int), if the value is null
if (key == "min_price" || key == "max_price") && value == nil { return }
if key == "avatar" {
if let urlString = value as? String {
avatar = urlString
}
return
}
super.setValue(value, forKey: key)
}
// MARK: - Description
override var description: String {
let keys = ["id", "name", "avatar", "gender", "level", "min_price", "max_price", "subject", "grades_shortname", "tags"]
return dictionaryWithValues(forKeys: keys).description
}
}
| mit |
tiny2n/UserDefaultsCompressor | UserDefaultsCompressor/Extension/UIImage+IUserDefaultsCompressor.swift | 1 | 557 | //
// UIImage+IUserDefaultsCompressor.swift
// UserDefaultsCompressor
//
// Created by Choi Joongkwan on 2016. 10. 18..
// Copyright © 2016년 Choi Joongkwan. All rights reserved.
//
import Foundation
import UIKit
extension UIImage: IUserDefaultsCompressor {
public func compress() -> Data? {
return UIImagePNGRepresentation(self)
}
public static func extract(compressed: Data?) -> UIImage? {
if let compressed = compressed {
return UIImage(data: compressed)
}
return nil
}
}
| mit |
Den-Ree/InstagramAPI | src/InstagramAPI/InstagramAPI/Example/ViewControllers/Location/LocationRecentCell.swift | 2 | 406 | //
// LocationRecentCell.swift
// InstagramAPI
//
// Created by Admin on 06.06.17.
// Copyright © 2017 ConceptOffice. All rights reserved.
//
import UIKit
class LocationRecentCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| mit |
BeezleLabs/HackerTracker-iOS | hackertracker/CalendarUtility.swift | 1 | 5494 | //
// CalendarUtility.swift
// hackertracker
//
// Created by caleb on 8/1/20.
// Copyright © 2020 Beezle Labs. All rights reserved.
//
import EventKit
import Foundation
import UIKit
struct CalendarUtility {
let eventStore = EKEventStore()
let status: EKAuthorizationStatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
func requestAuthorization() {
eventStore.requestAccess(to: EKEntityType.event) { _, error in
if let error = error {
print("Request authorization error: \(error.localizedDescription)")
}
}
}
func requestAuthorizationAndSave(htEvent: HTEventModel, view: HTEventDetailViewController) {
eventStore.requestAccess(to: EKEntityType.event) { authorized, error in
if authorized {
DispatchQueue.main.async {
self.addEventToCalendar(htEvent: htEvent, view: view)
}
}
if let error = error {
print("Request authorization error: \(error.localizedDescription)")
}
}
}
func addEvent(htEvent: HTEventModel, view: HTEventDetailViewController) {
switch status {
case .notDetermined:
requestAuthorizationAndSave(htEvent: htEvent, view: view)
case .authorized:
addEventToCalendar(htEvent: htEvent, view: view)
case .restricted, .denied:
deniedAccessAlert(view: view)
@unknown default:
break
}
}
private func addEventToCalendar(htEvent: HTEventModel, view: HTEventDetailViewController) {
let event = createEvent(htEvent: htEvent)
if !isDuplicate(newEvent: event) {
saveAlert(htEvent: htEvent, event: event, view: view)
} else {
duplicateAlert(htEvent: htEvent, view: view)
}
}
private func createEvent(htEvent: HTEventModel) -> EKEvent {
let event = EKEvent(eventStore: eventStore)
var notes = htEvent.description
let speakers = htEvent.speakers.map { $0.name }
if !speakers.isEmpty {
if speakers.count > 1 {
notes = "Speakers: \(speakers.joined(separator: ", "))\n\n\(htEvent.description)"
} else {
notes = "Speaker: \(speakers.first ?? "")\n\n\(htEvent.description)"
}
}
event.calendar = eventStore.defaultCalendarForNewEvents
event.startDate = htEvent.begin
event.endDate = htEvent.end
event.title = htEvent.title
event.location = htEvent.location.name
event.notes = notes
if !htEvent.links.isEmpty {
if htEvent.links.contains(where: { $0.url.contains("https://forum.defcon.org") }) {
if let link = htEvent.links.first(where: { $0.url.contains("https://forum.defcon.org") }), let url = URL(string: link.url) {
event.url = url
}
} else {
if let link = htEvent.links.first, let url = URL(string: link.url) {
event.url = url
}
}
}
return event
}
private func saveAlert(htEvent: HTEventModel, event: EKEvent, view: HTEventDetailViewController) {
let saveAlert = UIAlertController(
title: "Add \(htEvent.conferenceName) event to calendar",
message: htEvent.title, preferredStyle: .alert
)
saveAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
saveAlert.addAction(UIAlertAction(title: "Save", style: .default) { _ in
try? self.eventStore.save(event, span: .thisEvent)
})
view.present(saveAlert, animated: true)
}
private func deniedAccessAlert(view: HTEventDetailViewController) {
let deniedAlert = UIAlertController(
title: "Calendar access is currently disabled for HackerTracker",
message: "Select OK to view application settings", preferredStyle: .alert
)
deniedAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
deniedAlert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
})
view.present(deniedAlert, animated: true)
}
private func duplicateAlert(htEvent: HTEventModel, view: HTEventDetailViewController) {
let duplicateAlert = UIAlertController(
title: "Duplicate \(htEvent.conferenceName) event found in your calendar",
message: htEvent.title, preferredStyle: .alert
)
duplicateAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
view.present(duplicateAlert, animated: true)
}
private func isDuplicate(newEvent: EKEvent) -> Bool {
let predicate = eventStore
.predicateForEvents(withStart: newEvent.startDate, end: newEvent.endDate, calendars: nil)
let currentEvents = eventStore.events(matching: predicate)
let duplicateEvent = currentEvents
.contains(where: { $0.title == newEvent.title
&& $0.startDate == newEvent.startDate
&& $0.endDate == newEvent.endDate
})
return duplicateEvent
}
}
| gpl-2.0 |
sgr-ksmt/Alertift | Sources/Action.swift | 1 | 1641 | //
// Action.swift
// Alertift
//
// Created by Suguru Kishimoto on 4/27/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import Foundation
import UIKit
extension Alertift {
/// Action type for **Alert**, **ActionSheet**
///
/// - `default`: Default action(action title)
/// - destructive: Destructive action(action title)
/// - cancel: Cancel description(action title)
public enum Action {
typealias Handler = (UIAlertAction) -> Void
case `default`(String?)
case destructive(String?)
case cancel(String?)
init(title: String?) {
self = .default(title)
}
/// **UIAlertAction**'s title
private var title: String? {
switch self {
case .default(let title): return title
case .destructive(let title): return title
case .cancel(let title): return title
}
}
/// **UIAlertAction**'s style
private var style: UIAlertAction.Style {
switch self {
case .default( _): return .default
case .destructive( _): return .destructive
case .cancel( _): return .cancel
}
}
/// **Build UIAlertAction**
///
/// - Parameter actionHandler: Action handler for **UIAlertAction**
/// - Returns: Instance of **UIAlertAction**
func buildAlertAction(handler actionHandler: Action.Handler?) -> UIAlertAction {
return UIAlertAction(title: title, style: style, handler: actionHandler)
}
}
}
| mit |
i-schuetz/SwiftCharts | SwiftCharts/Axis/ChartAxisLayerDefault.swift | 1 | 16075 | //
// ChartAxisLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
This class allows customizing the layout of an axis layer and its contents. An example of how some of these settings affect the layout of a Y axis is shown below.
````
┌───────────────────────────────────────────────────────────────────┐
│ screenTop │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ ───────────────────────────────────────────────────────── │ │ labelsToAxisSpacingX
│ │ ◀───┼───┼──── similar for labelsToAxisSpacingY
│ │ Label 1 Label 2 Label 3 Label 4 Label 5 │ │
│ │ ◀───┼───┼──── labelsSpacing (only supported for X axes)
screenLeading ────┼─▶ │ Label A Label B Label C Label D Label E │ │
│ │ │ │
│ │ ◀────────────────────────────┼───┼──── axisTitleLabelsToLabelsSpacing
│ │ │ │
│ │ Title │ ◀─┼──── screenTrailing
│ └───────────────────────────────────────────────────────────┘ │
│ screenBottom │
└───────────────────────────────────────────────────────────────────┘
````
*/
open class ChartAxisSettings {
var screenLeading: CGFloat = 0
var screenTrailing: CGFloat = 0
var screenTop: CGFloat = 0
var screenBottom: CGFloat = 0
var labelsSpacing: CGFloat = 5
var labelsToAxisSpacingX: CGFloat = 5
var labelsToAxisSpacingY: CGFloat = 5
var axisTitleLabelsToLabelsSpacing: CGFloat = 5
var lineColor:UIColor = UIColor.black
var axisStrokeWidth: CGFloat = 2.0
var isAxisLineVisible: Bool = true
convenience init(_ chartSettings: ChartSettings) {
self.init()
self.labelsSpacing = chartSettings.labelsSpacing
self.labelsToAxisSpacingX = chartSettings.labelsToAxisSpacingX
self.labelsToAxisSpacingY = chartSettings.labelsToAxisSpacingY
self.axisTitleLabelsToLabelsSpacing = chartSettings.axisTitleLabelsToLabelsSpacing
self.screenLeading = chartSettings.leading
self.screenTop = chartSettings.top
self.screenTrailing = chartSettings.trailing
self.screenBottom = chartSettings.bottom
self.axisStrokeWidth = chartSettings.axisStrokeWidth
}
}
public typealias ChartAxisValueLabelDrawers = (scalar: Double, drawers: [ChartLabelDrawer])
/// Helper class to notify other layers about frame changes which affect content available space
public final class ChartAxisLayerWithFrameDelta {
let layer: ChartAxisLayer
let delta: CGFloat
init(layer: ChartAxisLayer, delta: CGFloat) {
self.layer = layer
self.delta = delta
}
}
extension Optional where Wrapped: ChartAxisLayerWithFrameDelta {
var deltaDefault0: CGFloat {
return self?.delta ?? 0
}
}
public enum AxisLabelsSpaceReservationMode {
case minPresentedSize /// Doesn't reserve less space than the min presented label width/height so far
case maxPresentedSize /// Doesn't reserve less space than the max presented label width/height so far
case fixed(CGFloat) /// Fixed value, ignores labels width/height
case current /// Reserves space for currently visible labels
}
public typealias ChartAxisValueLabelDrawersWithAxisLayer = (valueLabelDrawers: ChartAxisValueLabelDrawers, layer: ChartAxisLayer)
public struct ChartAxisLayerTapSettings {
public let expandArea: CGSize
let handler: ((ChartAxisValueLabelDrawersWithAxisLayer) -> Void)?
public init(expandArea: CGSize = CGSize(width: 10, height: 10), handler: ((ChartAxisValueLabelDrawersWithAxisLayer) -> Void)? = nil) {
self.expandArea = expandArea
self.handler = handler
}
}
/// A default implementation of ChartAxisLayer, which delegates drawing of the axis line and labels to the appropriate Drawers
open class ChartAxisLayerDefault: ChartAxisLayer {
open var axis: ChartAxis
var origin: CGPoint {
fatalError("Override")
}
var end: CGPoint {
fatalError("Override")
}
open var frame: CGRect {
return CGRect(x: origin.x, y: origin.y, width: width, height: height)
}
open var frameWithoutLabels: CGRect {
return CGRect(x: origin.x, y: origin.y, width: widthWithoutLabels, height: heightWithoutLabels)
}
open var visibleFrame: CGRect {
fatalError("Override")
}
/// Constant dimension between origin and end
var offset: CGFloat
open var currentAxisValues: [Double] = []
public let valuesGenerator: ChartAxisValuesGenerator
open var labelsGenerator: ChartAxisLabelsGenerator
let axisTitleLabels: [ChartAxisLabel]
let settings: ChartAxisSettings
// exposed for subclasses
var lineDrawer: ChartLineDrawer?
var labelDrawers: [ChartAxisValueLabelDrawers] = []
var axisTitleLabelDrawers: [ChartLabelDrawer] = []
let labelsConflictSolver: ChartAxisLabelsConflictSolver?
open weak var chart: Chart?
let labelSpaceReservationMode: AxisLabelsSpaceReservationMode
let clipContents: Bool
open var tapSettings: ChartAxisLayerTapSettings?
public var canChangeFrameSize: Bool = true
var widthWithoutLabels: CGFloat {
return width
}
var heightWithoutLabels: CGFloat {
return settings.axisStrokeWidth + settings.labelsToAxisSpacingX + settings.axisTitleLabelsToLabelsSpacing + axisTitleLabelsHeight
}
open var axisValuesScreenLocs: [CGFloat] {
return self.currentAxisValues.map{axis.screenLocForScalar($0)}
}
open var axisValuesWithFrames: [(axisValue: Double, frames: [CGRect])] {
return labelDrawers.map { axisValue, drawers in
(axisValue: axisValue, frames: drawers.map{$0.frame})
}
}
var visibleAxisValuesScreenLocs: [CGFloat] {
return currentAxisValues.reduce(Array<CGFloat>()) {u, scalar in
return u + [axis.screenLocForScalar(scalar)]
}
}
// smallest screen space between axis values
open var minAxisScreenSpace: CGFloat {
return axisValuesScreenLocs.reduce((CGFloat.greatestFiniteMagnitude, -CGFloat.greatestFiniteMagnitude)) {tuple, screenLoc in
let minSpace = tuple.0
let previousScreenLoc = tuple.1
return (min(minSpace, abs(screenLoc - previousScreenLoc)), screenLoc)
}.0
}
lazy private(set) var axisTitleLabelsHeight: CGFloat = {
return self.axisTitleLabels.reduce(0) { sum, label in
sum + label.textSize.height
}
}()
lazy private(set) var axisTitleLabelsWidth: CGFloat = {
return self.axisTitleLabels.reduce(0) { sum, label in
sum + label.textSize.width
}
}()
open func keepInBoundaries() {
axis.keepInBoundaries()
initDrawers()
chart?.view.setNeedsDisplay()
}
var width: CGFloat {
fatalError("override")
}
open var lineP1: CGPoint {
fatalError("override")
}
open var lineP2: CGPoint {
fatalError("override")
}
var height: CGFloat {
fatalError("override")
}
open var low: Bool {
fatalError("override")
}
/// Frame of layer after last update. This is used to detect deltas with the frame resulting from an update. Note that the layer's frame can be altered by only updating the model data (this depends on how the concrete axis layer calculates the frame), which is why this frame is not always identical to the layer's frame directly before calling udpate.
var lastFrame: CGRect = CGRect.zero
// NOTE: Assumes axis values sorted by scalar (can be increasing or decreasing)
public required init(axis: ChartAxis, offset: CGFloat, valuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, axisTitleLabels: [ChartAxisLabel], settings: ChartAxisSettings, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, labelSpaceReservationMode: AxisLabelsSpaceReservationMode, clipContents: Bool) {
self.axis = axis
self.offset = offset
self.valuesGenerator = valuesGenerator
self.labelsGenerator = labelsGenerator
self.axisTitleLabels = axisTitleLabels
self.settings = settings
self.labelsConflictSolver = labelsConflictSolver
self.labelSpaceReservationMode = labelSpaceReservationMode
self.clipContents = clipContents
self.lastFrame = frame
self.currentAxisValues = valuesGenerator.generate(axis)
}
open func update() {
prepareUpdate()
updateInternal()
postUpdate()
}
fileprivate func clearDrawers() {
lineDrawer = nil
labelDrawers = []
axisTitleLabelDrawers = []
}
func prepareUpdate() {
clearDrawers()
}
func updateInternal() {
initDrawers()
}
func postUpdate() {
lastFrame = frame
}
open func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) {
}
open func chartInitialized(chart: Chart) {
self.chart = chart
update()
}
/**
Draws the axis' line, labels and axis title label
- parameter context: The context to draw the axis contents in
- parameter chart: The chart that this axis belongs to
*/
open func chartViewDrawing(context: CGContext, chart: Chart) {
func draw() {
if settings.isAxisLineVisible {
if let lineDrawer = lineDrawer {
context.setLineWidth(CGFloat(settings.axisStrokeWidth))
lineDrawer.triggerDraw(context: context, chart: chart)
}
}
for (_, labelDrawers) in labelDrawers {
for labelDrawer in labelDrawers {
labelDrawer.triggerDraw(context: context, chart: chart)
}
}
for axisTitleLabelDrawer in axisTitleLabelDrawers {
axisTitleLabelDrawer.triggerDraw(context: context, chart: chart)
}
}
if clipContents {
context.saveGState()
context.addRect(visibleFrame)
context.clip()
draw()
context.restoreGState()
} else {
draw()
}
}
open func chartContentViewDrawing(context: CGContext, chart: Chart) {}
open func chartDrawersContentViewDrawing(context: CGContext, chart: Chart, view: UIView) {}
open func handleGlobalTap(_ location: CGPoint) {}
func initDrawers() {
fatalError("override")
}
func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer {
fatalError("override")
}
func generateAxisTitleLabelsDrawers(offset: CGFloat) -> [ChartLabelDrawer] {
fatalError("override")
}
/// Generates label drawers to be displayed on the screen. Calls generateDirectLabelDrawers to generate labels and passes result to an optional conflict solver, which maps the labels array to a new one such that the conflicts are solved. If there's no conflict solver returns the drawers unmodified.
func generateLabelDrawers(offset: CGFloat) -> [ChartAxisValueLabelDrawers] {
let directLabelDrawers = generateDirectLabelDrawers(offset: offset)
return labelsConflictSolver.map{$0.solveConflicts(directLabelDrawers)} ?? directLabelDrawers
}
/// Generates label drawers which correspond directly to axis values. No conflict solving.
func generateDirectLabelDrawers(offset: CGFloat) -> [ChartAxisValueLabelDrawers] {
fatalError("override")
}
open func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
fatalError("override")
}
open func zoom(_ scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) {
fatalError("override")
}
open func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
fatalError("override")
}
open func handlePanStart(_ location: CGPoint) {}
open func handlePanStart() {}
open func handlePanFinish() {}
open func handleZoomFinish() {}
open func handlePanEnd() {}
open func handleZoomEnd() {}
open func copy(_ axis: ChartAxis? = nil, offset: CGFloat? = nil, valuesGenerator: ChartAxisValuesGenerator? = nil, labelsGenerator: ChartAxisLabelsGenerator? = nil, axisTitleLabels: [ChartAxisLabel]? = nil, settings: ChartAxisSettings? = nil, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, labelSpaceReservationMode: AxisLabelsSpaceReservationMode? = nil, clipContents: Bool? = nil) -> ChartAxisLayerDefault {
return type(of: self).init(
axis: axis ?? self.axis,
offset: offset ?? self.offset,
valuesGenerator: valuesGenerator ?? self.valuesGenerator,
labelsGenerator: labelsGenerator ?? self.labelsGenerator,
axisTitleLabels: axisTitleLabels ?? self.axisTitleLabels,
settings: settings ?? self.settings,
labelsConflictSolver: labelsConflictSolver ?? self.labelsConflictSolver,
labelSpaceReservationMode: labelSpaceReservationMode ?? self.labelSpaceReservationMode,
clipContents: clipContents ?? self.clipContents
)
}
open func handleGlobalTap(_ location: CGPoint) -> Any? {
guard let tapSettings = tapSettings else {return nil}
if visibleFrame.contains(location) {
if let tappedLabelDrawers = (labelDrawers.filter{$0.drawers.contains{drawer in drawer.frame.insetBy(dx: -tapSettings.expandArea.width, dy: -tapSettings.expandArea.height).contains(location)}}).first {
tapSettings.handler?((valueLabelDrawers: tappedLabelDrawers, layer: self))
return tappedLabelDrawers
} else {
return nil
}
} else {
return nil
}
}
open func processZoom(deltaX: CGFloat, deltaY: CGFloat, anchorX: CGFloat, anchorY: CGFloat) -> Bool {
return false
}
open func processPan(location: CGPoint, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) -> Bool {
return false
}
}
| apache-2.0 |
devpunk/cartesian | cartesian/View/DrawProject/Menu/VDrawProjectMenuNodes.swift | 1 | 4301 | import UIKit
class VDrawProjectMenuNodes:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private var model:MDrawProjectMenuNodes?
private weak var controller:CDrawProject!
private weak var collectionView:VCollection!
private let kRows:CGFloat = 2
private let kDeselectTime:TimeInterval = 0.2
init(controller:CDrawProject)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceHorizontal = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerCell(cell:VDrawProjectMenuNodesCell.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
}
addSubview(collectionView)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
let height:CGFloat = bounds.maxY
let cellSide:CGFloat = height / kRows
let cellSize:CGSize = CGSize(width:cellSide, height:cellSide)
flow.itemSize = cellSize
}
super.layoutSubviews()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MDrawProjectMenuNodesItem
{
let item:MDrawProjectMenuNodesItem = model!.items[index.item]
return item
}
//MARK: public
func refresh()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.model = MDrawProjectMenuNodes()
DispatchQueue.main.async
{ [weak self] in
self?.collectionView.reloadData()
}
}
}
//MARK: collectionView delegate
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
guard
let count:Int = model?.items.count
else
{
return 0
}
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MDrawProjectMenuNodesItem = modelAtIndex(index:indexPath)
let cell:VDrawProjectMenuNodesCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VDrawProjectMenuNodesCell.reusableIdentifier,
for:indexPath) as! VDrawProjectMenuNodesCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
collectionView.isUserInteractionEnabled = false
let item:MDrawProjectMenuNodesItem = modelAtIndex(index:indexPath)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kDeselectTime)
{ [weak collectionView] in
collectionView?.selectItem(
at:nil,
animated:true,
scrollPosition:UICollectionViewScrollPosition())
collectionView?.isUserInteractionEnabled = true
}
if item.available
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.controller.addNode(
entityName:item.entityName)
}
}
else
{
controller.viewProject.showStore(purchase:item)
}
}
}
| mit |
MessageKit/MessageKit | Sources/Views/InsetLabel.swift | 1 | 1399 | // MIT License
//
// Copyright (c) 2017-2019 MessageKit
//
// 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 InsetLabel: UILabel {
open var textInsets: UIEdgeInsets = .zero {
didSet { setNeedsDisplay() }
}
open override func drawText(in rect: CGRect) {
let insetRect = rect.inset(by: textInsets)
super.drawText(in: insetRect)
}
}
| mit |
netease-app/NIMSwift | Example/Pods/CFWebImage/CFWebImage/Classes/CFWebImage.swift | 1 | 540 | //
// CFWebImage.swift
// CFWebImage
//
// Created by chengfei.heng on 11/22/2016.
// Copyright (c) 2016 chengfei.heng. All rights reserved.
//
import UIKit
import SDWebImage
public extension UIImageView {
@nonobjc
public func cf_setImage(url:NSURL,placeHolderImage:UIImage?){
self.sd_setImage(with: url as URL, placeholderImage: placeHolderImage)
}
@nonobjc
public func cf_setImage(url:URL,placeHolderImage:UIImage?){
self.sd_setImage(with: url, placeholderImage: placeHolderImage)
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/01236-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 12 | 540 | // 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 f<g {
{
}
{
{
}
}
{
}
class d { { }
func a {
}
let c = a
{
{
{
}
}
}
protocol a : a {
}
protocol a {
}
{
}
{
}
{
}
{
}
{
}
{
}
{
{
}
}
{
}
{
}
{
}
{
}
{
{
}
{
}
{
{
}
}
{
}
{
}
{
}
{
}
{
{
}
}
{
}
{
{
}
}
{
}
{
{
}
}
{
{
}
{
}
}
{
}
{
}
{
{
}
}
{
}
{
}
{
}
{
{
}
}
{
}
{
{
}
{
}
{
}
{
}
{
{
}
}
{
}
{
}
{
{
}
}
}
}
{
}
{
}
{
}
{
}
{
{
}
}
{
}
{
}
func a< > ( ) -> c
| mit |
cpascoli/WeatherHype | WeatherHype/Classes/Model/ForecastResults.swift | 1 | 263 | //
// ForecastResults.swift
// WeatherHype
//
// Created by Carlo Pascoli on 27/09/2016.
// Copyright © 2016 Carlo Pascoli. All rights reserved.
//
import Foundation
class ForecastResults: NSObject {
var city:City?
var data:[WeatherData]?
}
| apache-2.0 |
bartekchlebek/SwiftHelpers | Source/SequenceType/SequenceType+Find.swift | 1 | 203 | extension Sequence {
public func findFirst(_ evaluate: (Iterator.Element) -> Bool) -> Iterator.Element? {
for element in self {
if evaluate(element) {
return element
}
}
return nil
}
}
| mit |
iWeslie/Ant | Ant/Ant/LunTan/Detials/Controller/CarServiceDVC.swift | 1 | 8539 | //
// CarServiceDVC.swift
// Ant
//
// Created by Weslie on 2017/8/4.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class CarServiceDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
override func viewDidLoad() {
super.viewDidLoad()
loadDetialTableView()
let view = Menu()
self.tabBarController?.tabBar.isHidden = true
view.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(view)
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "CarServiceBasicInfo", bundle: nil), forCellReuseIdentifier: "carServiceBasicInfo")
tableView?.register(UINib(nibName: "CarServiceDetial", bundle: nil), forCellReuseIdentifier: "carServiceDetial")
tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 3
case 2: return 5
case 4: return 10
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6)
let urls = [
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg",
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png",
"http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg",
"http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg",
"http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png"
]
var urlArray: [URL] = [URL]()
for str in urls {
let url = URL(string: str)
urlArray.append(url!)
}
return LoopView(images: urlArray, frame: frame, isAutoScroll: true)
case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情介绍"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系人方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return UIScreen.main.bounds.width * 0.6
case 1:
return 30
case 2:
return 30
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceBasicInfo")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceDetial")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo")
default: break
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction")
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
// guard modelInfo.con else {
// <#statements#>
// }
if let contact = modelInfo?.connactDict[indexPath.row] {
if let key = contact.first?.key{
connactoptions.con_Ways.text = key
}
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return 60
case 1: return 100
case 2: return 40
default: return 20
}
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
}
| apache-2.0 |
leoru/Brainstorage | Brainstorage-iOS/Vendor/PullToRefreshSwift/UIScrollViewExtension.swift | 1 | 1625 | //
// PullToRefreshConst.swift
// PullToRefreshSwift
//
// Created by Yuji Hato on 12/11/14.
//
import Foundation
import UIKit
extension UIScrollView {
private var pullToRefreshView: PullToRefreshView? {
get {
var pullToRefreshView = viewWithTag(PullToRefreshConst.tag)
return pullToRefreshView as? PullToRefreshView
}
}
func addPullToRefresh(refreshCompletion :(() -> ())) {
let refreshViewFrame = CGRectMake(0, -PullToRefreshConst.height, self.frame.size.width, PullToRefreshConst.height)
var refreshView = PullToRefreshView(refreshCompletion: refreshCompletion, frame: refreshViewFrame)
refreshView.tag = PullToRefreshConst.tag
addSubview(refreshView)
}
func startPullToRefresh() {
pullToRefreshView?.state = .Refreshing
}
func stopPullToRefresh() {
pullToRefreshView?.state = .Normal
}
// If you want to PullToRefreshView fixed top potision, Please call this function in scrollViewDidScroll
func fixedPullToRefreshViewForDidScroll() {
if PullToRefreshConst.fixedTop {
if self.contentOffset.y < -PullToRefreshConst.height {
if var frame = pullToRefreshView?.frame {
frame.origin.y = self.contentOffset.y
pullToRefreshView?.frame = frame
}
} else {
if var frame = pullToRefreshView?.frame {
frame.origin.y = -PullToRefreshConst.height
pullToRefreshView?.frame = frame
}
}
}
}
}
| mit |
mcudich/HeckelDiff | Source/UITableView+Diff.swift | 1 | 1572 | //
// UITableView+Diff.swift
// HeckelDiff
//
// Created by Matias Cudich on 11/23/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
public extension UITableView {
/// Applies a batch update to the receiver, efficiently reporting changes between old and new.
///
/// - parameter old: The previous state of the table view.
/// - parameter new: The current state of the table view.
/// - parameter section: The section where these changes took place.
/// - parameter animation: The animation type.
/// - parameter reloadUpdated: Whether or not updated cells should be reloaded (default: true)
func applyDiff<T: Collection>(_ old: T, _ new: T, inSection section: Int, withAnimation animation: UITableView.RowAnimation, reloadUpdated: Bool = true) where T.Iterator.Element: Hashable, T.Index == Int {
let update = ListUpdate(diff(old, new), section)
beginUpdates()
deleteRows(at: update.deletions, with: animation)
insertRows(at: update.insertions, with: animation)
for move in update.moves {
moveRow(at: move.from, to: move.to)
}
endUpdates()
// reloadItems is done separately as the update indexes returne by diff() are in respect to the
// "after" state, but the collectionView.reloadItems() call wants the "before" indexPaths.
if reloadUpdated && update.updates.count > 0 {
beginUpdates()
reloadRows(at: update.updates, with: animation)
endUpdates()
}
}
}
#endif
| mit |
canatac/SimpleForm | simpleForm/simpleForm/MasterViewController.swift | 1 | 9497 | //
// MasterViewController.swift
// simpleForm
//
// Created by Can ATAC on 06/07/2015.
// Copyright (c) 2015 Can ATAC. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
cell.textLabel!.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit |
evering7/Speak | SourceRSS+CoreDataClass.swift | 1 | 4713 | //
// SourceRSS+CoreDataClass.swift
// iSpeaking
//
// Created by JianFei Li on 26/04/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import CoreData
import UIKit
@objc(SourceFeedDisk)
public class SourceFeedDisk: NSManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<SourceFeedDisk> {
return NSFetchRequest<SourceFeedDisk>(entityName: "SourceFeedDisk")
}
// for coredata use
// db 2, feed 9, svr 3, total 14
@NSManaged public var feed_Title: String?
@NSManaged public var feed_Language: String?
@NSManaged public var feed_URL: String?
@NSManaged public var feed_Author: String?
@NSManaged public var feed_Tags: String?
@NSManaged public var feed_IsRSSorAtom : NSNumber
@NSManaged public var svr_Likes: Int64
@NSManaged public var svr_Dislikes: Int64
@NSManaged public var svr_SubscribeCount: Int64
@NSManaged public var db_ID: Int64
@NSManaged public var db_DownloadedXMLFileName: String?
@NSManaged public var feed_UpdateTime: NSDate?
// @NSManaged public var isLastUpdateSuccess: NSNumber
@NSManaged public var feed_IsDownloadSuccess: NSNumber
@NSManaged public var feed_DownloadTime: NSDate?
var feed_IsRSSorAtomBool: Bool {
get { return Bool(feed_IsRSSorAtom) }
set { self.feed_IsRSSorAtom = NSNumber(value: newValue)}
}
var feed_IsDownloadSuccessBool: Bool {
get {return Bool(feed_IsDownloadSuccess)}
set {self.feed_IsDownloadSuccess = NSNumber(value: newValue)}
}
func loadSourceFeed_FromDisk_ToMemory() -> SourceFeedMem {
let memSourceRSS: SourceFeedMem = SourceFeedMem()
memSourceRSS.feed_Title = self.feed_Title!
memSourceRSS.feed_Language = self.feed_Language!
memSourceRSS.feed_URL = self.feed_URL!
memSourceRSS.feed_Author = self.feed_Author!
memSourceRSS.feed_Tags = self.feed_Tags!
memSourceRSS.feed_IsRSSorAtom = self.feed_IsRSSorAtomBool
memSourceRSS.svr_Likes = self.svr_Likes
memSourceRSS.svr_Dislikes = self.svr_Dislikes
memSourceRSS.svr_SubscribeCount = self.svr_SubscribeCount
memSourceRSS.db_ID = self.db_ID
memSourceRSS.db_DownloadedXMLFileName = self.db_DownloadedXMLFileName!
memSourceRSS.feed_UpdateTime = self.feed_UpdateTime! as Date // indicate the web feed self update time
// memSourceRSS.isLastUpdateSuccess = self.isLastUpdateSuccess2
memSourceRSS.feed_IsDownloadSuccess = self.feed_IsDownloadSuccessBool
memSourceRSS.feed_DownloadTime = self.feed_DownloadTime! as Date
return memSourceRSS
}
}
class SourceFeedMem: NSObject{
// for memory use
var feed_Title: String = ""
var feed_Language: String = ""
var feed_URL: String = ""
var feed_Author: String = "no name"
var feed_Tags: String = ""
var svr_Likes: Int64 = 0
var svr_Dislikes: Int64 = 0
var svr_SubscribeCount: Int64 = 0
var db_ID: Int64 = 0
var db_DownloadedXMLFileName = ""
var feed_UpdateTime: Date = Date()
// var isLastUpdateSuccess: Bool = false
var feed_IsDownloadSuccess: Bool = false
var feed_DownloadTime: Date = Date()
var feed_IsRSSorAtom : Bool = true // true indicate RSS, false indicate Atom
var mem_rssFeed: RSSFeed = RSSFeed()
var mem_atomFeed: AtomFeed = AtomFeed()
func downloadFeedFile_FromWeb_ToMemory() {
// 1. get path of local xml file
let tempPath = getRSSxmlFileURLfromLastComponent(lastPathCompo: self.db_DownloadedXMLFileName).path
self.feed_IsDownloadSuccess = false
if self.db_DownloadedXMLFileName == "" ||
!isFileExist(fileFullPath: tempPath){ // generate file name,too if the file not exist
let strFileURL = getUnusedRandomFeedXmlFileURL()
printLog(message: "get unused random rss xml file url \(strFileURL.path)")
printLog(message: "last path component \(strFileURL.lastPathComponent)")
// 6. use StructSourceRSS, register some info of the file
self.db_DownloadedXMLFileName = strFileURL.lastPathComponent
}
HttpDownloader.loadXMLFileSync(sourceFeed: self, completion: {
(path, error) in
if error == nil{
printLog(message: "Successfully download to \(path)")
self.feed_IsDownloadSuccess = true
return
}
return
})
}
}
| mit |
vfn/Kingfisher | Kingfisher/UIImageView+Kingfisher.swift | 2 | 8077 | //
// UIImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <onevcat@gmail.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
// MARK: - Set Images
/**
* Set image to use from web.
*/
public extension UIImageView {
/**
Set an image with a URL.
It will ask for Kingfisher's manager to get the image for the URL.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use.
:param: URL The URL of image.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL and a placeholder image.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placaholder image and options.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placeholder image, options and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image with a URL, a placeholder image, options, progress handler and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
image = placeholderImage
kf_setWebURL(URL)
let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil {
sSelf.image = image;
}
completionHandler?(image: image, error: error, cacheType:cacheType, imageURL: imageURL)
})
})
return task
}
}
// MARK: - Associated Object
private var lastURLkey: Void?
public extension UIImageView {
/// Get the image URL binded to this image view.
public var kf_webURL: NSURL? {
get {
return objc_getAssociatedObject(self, &lastURLkey) as? NSURL
}
}
private func kf_setWebURL(URL: NSURL) {
objc_setAssociatedObject(self, &lastURLkey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
// MARK: - Deprecated
public extension UIImageView {
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit |
iosdevzone/SwiftStandardLibraryPlaygrounds | SequenceAndCollectionFunctions.playground/section-54.swift | 2 | 75 | zeroOneTwoThree = [0,1,2,3]
var threeTwoOneZero = reverse(zeroOneTwoThree)
| mit |
lauracpierre/FA_TokenInputView | Pod/Classes/FA_TokenLabel.swift | 1 | 322 | //
// FA_TokenLabel.swift
// Pods
//
// Created by Pierre Laurac on 9/14/16.
//
//
import Foundation
class FA_TokenLabel: UILabel {
override var canBecomeFirstResponder : Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
| mit |
KeithPiTsui/Pavers | Pavers/Sources/UI/Styles/lenses/CGSizeLenses.swift | 2 | 382 | // swiftlint:disable type_name
import PaversFRP
import UIKit
extension CGSize {
public enum lens {
public static let width = Lens<CGSize, CGFloat>(
view: { $0.width },
set: { .init(width: $0, height: $1.height) }
)
public static let height = Lens<CGSize, CGFloat>(
view: { $0.height },
set: { .init(width: $1.width, height: $0) }
)
}
}
| mit |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/Material+String.swift | 1 | 2549 | /*
* 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 CosmicMind 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
extension String {
/**
:name: trim
*/
public var trimmed: String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/**
:name: lines
*/
public var lines: [String] {
return components(separatedBy: CharacterSet.newlines)
}
/**
:name: firstLine
*/
public var firstLine: String? {
return lines.first?.trimmed
}
/**
:name: lastLine
*/
public var lastLine: String? {
return lines.last?.trimmed
}
/**
:name: replaceNewLineCharater
*/
public func replaceNewLineCharater(separator: String = " ") -> String {
return components(separatedBy: CharacterSet.whitespaces).joined(separator: separator).trimmed
}
/**
:name: replacePunctuationCharacters
*/
public func replacePunctuationCharacters(separator: String = "") -> String {
return components(separatedBy: CharacterSet.punctuationCharacters).joined(separator: separator).trimmed
}
}
| gpl-3.0 |
TwoRingSoft/shared-utils | Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/FeedbackConfiguration.swift | 1 | 3473 | //
// FeedbackConfiguration.swift
// Pods
//
// Created by Michael Liberatore on 7/8/16.
//
//
/// Encapsulates configuration properties for all feedback to be sent.
public struct FeedbackConfiguration {
/// Encapsulates body content of the feedback submission. Suitable for an email body.
public struct Body {
/// The initial body text of the message. The text is interpreted as either plain text or HTML depending on the value of `isHTML`.
public var content: String
/// `true` if `content` contains HTML or `false` if it is plain text.
public var isHTML: Bool
/// Initializes a new `Body`.
///
/// - Parameters:
/// - content: The initial body text of the message. The text is interpreted as either plain text or HTML depending on the value of `isHTML`.
/// - isHTML: `true` if `content` contains HTML or `false` if it is plain text.
public init(_ content: String, isHTML: Bool = false) {
self.content = content
self.isHTML = isHTML
}
}
/// The value of the default parameter for `title` in the initializer.
public static let DefaultTitle = "Bug Report"
/// A file name without an extension for the screenshot or annotated screenshot.
public var screenshotFileName: String
/// The recipients of the feedback submission. Suitable for email recipients in the "To:" field.
public var recipients: [String]?
/// A short, optional title of the feedback submission. Suitable for an email subject.
public var title: String?
/// An optional body of the feedback submission.
public var body: Body?
/// A file name without an extension for the logs text file.
public var logsFileName: String
/// A dictionary of additional information provided by the application developer.
public var additionalInformation: [String: AnyObject]?
/// The modal presentation style for the feedback collection screen.
public let presentationStyle: UIModalPresentationStyle
/**
Initializes a `FeedbackConfiguration` with optional default values.
- parameter screenshotFileName: The file name of the screenshot.
- parameter recipients: The recipients of the feedback submission.
- parameter title: The title of the feedback.
- parameter body: The default body text.
- parameter logsFileName: The file name of the logs text file.
- parameter additionalInformation: Any additional information you want to capture.
- parameter presentationStyle: The modal presentation style for the the feedback collection screen.
*/
public init(screenshotFileName: String = "Screenshot",
recipients: [String],
title: String? = FeedbackConfiguration.DefaultTitle,
body: Body? = nil,
logsFileName: String = "logs",
additionalInformation: [String: AnyObject]? = nil,
presentationStyle: UIModalPresentationStyle = .fullScreen) {
self.screenshotFileName = screenshotFileName
self.recipients = recipients
self.title = title
self.body = body
self.logsFileName = logsFileName
self.additionalInformation = additionalInformation
self.presentationStyle = presentationStyle
}
}
| mit |
dreamsxin/swift | test/Interpreter/objc_class_properties_runtime.swift | 3 | 1823 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %clang -arch x86_64 -mmacosx-version-min=10.11 -isysroot %sdk -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %swiftc_driver -target $(echo '%target-triple' | sed -E -e 's/macosx10.(9|10).*/macosx10.11/') -sdk %sdk -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out
// RUN: %t/a.out
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import StdlibUnittest
import ObjCClasses
class SwiftClass : ProtoWithClassProperty {
static var getCount = 0
static var setCount = 0
private static var _value: CInt = 0
@objc class func reset() {
getCount = 0
setCount = 0
_value = 0
}
@objc class var value: CInt {
get {
getCount += 1
return _value
}
set {
setCount += 1
_value = newValue
}
}
@objc class var optionalClassProp: Bool {
return true
}
}
class Subclass : ClassWithClassProperty {
static var getCount = 0
static var setCount = 0
override class func reset() {
getCount = 0
setCount = 0
super.reset()
}
override class var value: CInt {
get {
getCount += 1
return super.value
}
set {
setCount += 1
super.value = newValue
}
}
override class var optionalClassProp: Bool {
return true
}
}
var ClassProperties = TestSuite("ClassProperties")
ClassProperties.test("runtime")
.skip(.osxMinorRange(10, 0...10, reason: "not supported on 10.10 or below"))
.code {
let theClass: AnyObject = SwiftClass.self
let prop = class_getProperty(object_getClass(theClass), "value")
expectNotEmpty(prop)
let nameAsCString = property_getName(prop)!
expectNotEmpty(nameAsCString)
expectEqual("value", String(cString: nameAsCString))
}
runAllTests()
| apache-2.0 |
chengxianghe/MissGe | MissGe/MissGe/Class/Helper/XHUploadImagesHelper.swift | 1 | 9767 | //
// XHUploadImagesHelper.swift
// MissGe
//
// Created by chengxianghe on 2017/4/25.
// Copyright © 2017年 cn. All rights reserved.
//
import Foundation
import TUNetworking
enum XHUploadImageMode: UInt {
/** 失败自动重传 */
case retry
/** 失败直接忽略 */
case ignore
}
typealias XHUploadImageCompletion = (_ successImageUrls: [XHUploadImageModel]?, _ failedImages: [XHUploadImageModel]?) -> Void
typealias XHUploadImageProgress = (_ totals: NSInteger, _ completions: NSInteger) -> Void
class XHUploadImagesHelper: NSObject {
//外部参数
var imageArray: [String]! // 需要上传的图片数组 里面存本地文件的地址
var mode = XHUploadImageMode.ignore
var completion: XHUploadImageCompletion?
var progress: XHUploadImageProgress?
var maxTime: TimeInterval = 60.0 // 最长时间限制 默认单张60s
// 内部参数
var requestArray = [XHUploadImageRequest]() // 已经发起的请求
var requestReadyArray = [XHUploadImageRequest]() // 准备发起的请求
var resultModelArray = [XHUploadImageModel]() // 请求回来的保存的数据
var maxNum: Int = 3 // 同时最大并发数 默认 kDefaultUploadMaxNum
var isEnd = false // 是否已经结束请求
func cancelOneRequest(_ request: XHUploadImageRequest) {
request.cancel()
}
func cancelUploadRequest() {
// 先取消 结束回调
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(endUpload), object: nil)
self.isEnd = true
for request in self.requestArray {
self.cancelOneRequest(request)
}
self.completion = nil
self.progress = nil
}
func removeRequest(_ request: XHUploadImageRequest) {
self.requestArray.remove(at: self.requestArray.index(of: request)!)
self.cancelOneRequest(request)
if (self.requestReadyArray.count > 0 && self.requestArray.count < self.maxNum) {
let req = self.requestReadyArray.first!
self.requestArray.append(req)
self.startRequest(req)
self.requestReadyArray.remove(at: self.requestReadyArray.index(of: req)!)
}
}
func addRequest(_ request: XHUploadImageRequest) {
if (self.requestArray.count < self.maxNum) {
self.requestArray.append(request)
self.startRequest(request)
} else {
self.requestReadyArray.append(request)
}
}
func startRequest(_ request: XHUploadImageRequest) {
// [request cancelRequest];
print("*********正在上传图index:\(request.imageIndex) ....")
request.upload(constructingBody: { (formData: AFMultipartFormData) in
// if request.imageData != nil {
// formData.appendPart(withFileData: request.imageData!, name: "image", fileName: "uploadImg_\(request.imageIndex).gif", mimeType: "image/gif")
// } else if request.imagePath != nil {
do {
try formData.appendPart(withFileURL: URL.init(fileURLWithPath: request.imagePath!), name: "image", fileName: request.name, mimeType: request.isGif ? "image/gif" : "image/jpeg")
}
catch let error as NSError {
print(error)
}
// } else {
// print("上传的图片没有数据imagePath、imageData不可都为nil")
// }
}, progress: { (progress) in
print("progressView: \(progress.fractionCompleted)")
}, success: { (baseRequest, responseObject) in
print("上传成功");
self.checkResult(request)
}) { (baseRequest, error) in
print("上传失败:\(error.localizedDescription)");
self.checkResult(request)
}
}
open func uploadImages(images: [String], uploadMode: XHUploadImageMode, progress: XHUploadImageProgress?, completion: XHUploadImageCompletion?) {
self.uploadImages(images: images, uploadMode: uploadMode, maxTime: TimeInterval(images.count * 60), progress: progress, completion: completion)
}
open func uploadImages(images: [String], uploadMode: XHUploadImageMode, maxTime: TimeInterval, progress: XHUploadImageProgress?, completion: XHUploadImageCompletion?) {
self.requestArray.removeAll()
self.requestReadyArray.removeAll()
self.resultModelArray.removeAll()
self.completion = completion;
self.progress = progress;
self.mode = uploadMode;
self.imageArray = images;
self.maxTime = maxTime;
self.isEnd = false;
// TODO: 根据网络环境 决定 同时上传数量
self.maxNum = 3;
// 定时回调endUpload
self.perform(#selector(endUpload), with: nil, afterDelay: maxTime)
var i = 0
for str in images {
let request = XHUploadImageRequest.init()
request.imagePath = str
request.imageIndex = i
request.name = (str as NSString).lastPathComponent
request.isGif = (str as NSString).pathExtension.uppercased() == "GIF"
self.addRequest(request)
i = i + 1
}
// 先回调一下progress
self.progress?(self.imageArray.count, self.resultModelArray.count);
}
func checkResult(_ request: XHUploadImageRequest) {
if (self.isEnd) {
return;
}
if (self.mode == .retry && request.resultImageUrl == nil) {
// 失败自动重传
self.startRequest(request)
return;
} else {
let model = XHUploadImageModel.init()
model.imageIndex = request.imageIndex;
model.imagePath = request.imagePath;
model.resultImageUrl = request.resultImageUrl;
model.resultImageId = request.resultImageId;
self.resultModelArray.append(model)
self.removeRequest(request)
}
// 进度回调
self.progress?(self.imageArray.count, self.resultModelArray.count);
if (self.resultModelArray.count == self.imageArray.count) {
self.endUpload()
}
}
@objc func endUpload() {
// 全部完成
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(endUpload), object: nil)
// 排序
self.resultModelArray.sort { (obj1, obj2) -> Bool in
// 从小到大
return obj1.imageIndex > obj2.imageIndex;
}
var successImages = [XHUploadImageModel]()
var failedImages = [XHUploadImageModel]()
for model in resultModelArray {
if (model.resultImageUrl != nil) {
successImages.append(model)
} else {
failedImages.append(model)
}
}
self.completion?(successImages,failedImages);
self.cancelUploadRequest()
}
}
//mark: - Class: GMBUploadImageModel
class XHUploadImageModel: NSObject {
var imageIndex: Int = 0
var imagePath: String!
var resultImageUrl: String? // 接口返回的 图片地址
var resultImageId: String? // 接口返回的 图片id
}
/// imageData和imagePath不可都为nil
class XHUploadImageRequest: TUUploadRequest {
var imageIndex: Int = 0
var isGif: Bool = false
var name: String = ""
var imagePath: String? // 上传的普通图片路径
// var imageData: Data? // 上传的gif图片data
var resultImageUrl: String? // 接口返回的 图片地址
var resultImageId: String? // 接口返回的 图片id
override func requestUrl() -> String? {
let str = "http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=upload&a=postUpload&token="
return str.appending(MLNetConfig.shareInstance.token)
}
// 请求成功后返回的参数
override func requestHandleResult() {
if(self.responseObject == nil) {
return ;
}
/**
{
"result":"200",
"msg":"\u56fe\u50cf\u4e0a\u4f20\u6210\u529f",
"content":
{
"image_name":"uploadImg_0.png",
"url":"http:\/\/img.gexiaojie.com\/post\/2016\/0718\/160718100723P003873V86.png",
"image_id":25339}
}
}
*/
guard let result = self.responseObject as? [String:Any] else {
return
}
guard let temp = result["content"] as? [String:Any] else {
return
}
if (temp["url"] != nil) {
self.resultImageUrl = temp["url"] as? String;
if let tempImageId = temp["image_id"] as? Int {
self.resultImageId = "\(tempImageId)"
} else if let tempImageId = temp["image_id"] as? String {
self.resultImageId = tempImageId
}
print("*********上传图index:\(self.imageIndex) 成功!:\(String(describing: self.resultImageUrl))(id:\(String(describing: self.resultImageId))))")
// print("*********上传图index:%ld 成功!:%@(id:%d)", (long)self.imageIndex, self.resultImageUrl, (int)self.resultImageId);
} else {
print("*********上传图index:\(self.imageIndex) 失败!:\(String(describing: self.imagePath))")
}
}
}
| mit |
emilstahl/swift | validation-test/compiler_crashers_fixed/1992-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 12 | 286 | // RUN: not %target-swift-frontend %s -parse
// 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 A<h: SequenceType where h: A where T -> {
func g(f.Type) -> Self
| apache-2.0 |
emilstahl/swift | test/Serialization/search-paths-relative.swift | 20 | 1514 | // RUN: rm -rf %t && mkdir -p %t/secret
// RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift
// RUN: mkdir -p %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/
// RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias
// RUN: cd %t/secret && %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I . -F ../Frameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options -Xcc -DDUMMY
// RUN: %target-swift-frontend %s -parse -I %t
// Check the actual serialized search paths.
// RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule > %t/has_xref.swiftmodule.txt
// RUN: FileCheck %s < %t/has_xref.swiftmodule.txt
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t/has_xref.swiftmodule.txt
// XFAIL: linux
import has_xref
numeric(42)
// CHECK-LABEL: <OPTIONS_BLOCK
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '{{.+}}/secret'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-DDUMMY'
// CHECK: </OPTIONS_BLOCK>
// CHECK-LABEL: <INPUT_BLOCK
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1/> blob data = '{{.+}}/secret/../Frameworks'
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0/> blob data = '{{.+}}/secret/.'
// CHECK: </INPUT_BLOCK>
// NEGATIVE-NOT: '.'
// NEGATIVE-NOT: '../Frameworks'
| apache-2.0 |
kyuridenamida/atcoder-tools | tests/resources/test_codegen/template.swift | 1 | 250 | import Foundation
func solve({{ formal_arguments }}) {
}
func main() {
func readString() -> String { "" }
func readInt() -> Int { 0 }
func readDouble() -> Double { 0 }
{{input_part}}
_ = solve({{ actual_arguments }})
}
main()
| mit |
MoathOthman/MOHUD | Demo/MOHUDDemo/ViewController.swift | 1 | 2895 | //
// ViewController.swift
// MOHUDDemo
//
// Created by Moath_Othman on 9/21/15.
// Copyright © 2015 Moba. All rights reserved.
//
import UIKit
//import MOHUD
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showDefault(_ sender: AnyObject) {
MOHUD.show()
// MOHUD.setBlurStyle(.Light)
MOHUD.hideAfter(3)
}
@IBAction func showWithCancelAndContinue(_ sender: AnyObject) {
MOHUD.show(true)
MOHUD.setBlurStyle(.dark)
MOHUD.onCancel = {
debugPrint("User Canceled")
}
MOHUD.onContinoue = {
debugPrint("User want to contniue without the progress indicator ")
}
}
@IBAction func showWithStatus(_ sender: AnyObject) {
MOHUD.showWithStatus("Processing")
MOHUD.hideAfter(3)
}
@IBAction func showSuccess(_ sender: AnyObject) {
MOHUD.showSuccess("You Made it so now you can fly")
}
@IBAction func showSubtitle(_ sender: AnyObject) {
MOHUD.showSubtitle(title: "Connection", subtitle: "Please Wait")
MOHUD.hideAfter(3)
}
@IBAction func showFailure(_ sender: AnyObject) {
MOHUD.showWithError("Failed :(")
}
@IBOutlet weak var showFailure: UIButton!
}
@IBDesignable
class GradientView: UIView {
override func draw(_ rect: CGRect) {
//2 - get the current context
let startColor = UIColor ( red: 0.1216, green: 0.1294, blue: 0.1412, alpha: 1.0 )
let endColor = UIColor ( red: 0.4745, green: 0.7412, blue: 0.8353, alpha: 1.0 )
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray,
locations: colorLocations)
//6 - draw the gradient
let startPoint = CGPoint.zero
let endPoint = CGPoint(x:self.bounds.width
, y:self.bounds.height)
context?.drawLinearGradient(gradient!,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
}
}
| mit |
JamieScanlon/AugmentKit | AugmentKit/Renderer/Render Modules/AnchorsRenderModule.swift | 1 | 36454 | //
// AnchorsRenderModule.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import ARKit
import AugmentKitShader
import MetalKit
class AnchorsRenderModule: RenderModule, SkinningModule {
static var identifier = "AnchorsRenderModule"
//
// Setup
//
var moduleIdentifier: String {
return AnchorsRenderModule.identifier
}
var renderLayer: Int {
return 11
}
var state: ShaderModuleState = .uninitialized
var sharedModuleIdentifiers: [String]? = [SharedBuffersRenderModule.identifier]
var renderDistance: Double = 500
var errors = [AKError]()
// The number of anchor instances to render
private(set) var anchorInstanceCount: Int = 0
func initializeBuffers(withDevice aDevice: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) {
guard device == nil else {
return
}
state = .initializing
device = aDevice
// Calculate our uniform buffer sizes. We allocate `maxInFlightFrames` instances for uniform
// storage in a single buffer. This allows us to update uniforms in a ring (i.e. triple
// buffer the uniforms) so that the GPU reads from one slot in the ring wil the CPU writes
// to another. Anchor uniforms should be specified with a max instance count for instancing.
// Also uniform storage must be aligned (to 256 bytes) to meet the requirements to be an
// argument in the constant address space of our shading functions.
let materialUniformBufferSize = RenderModuleConstants.alignedMaterialSize * maxInFlightFrames
let jointTransformBufferSize = Constants.alignedJointTransform * Constants.maxJointCount * maxInFlightFrames
let effectsUniformBufferSize = Constants.alignedEffectsUniformSize * maxInFlightFrames
let environmentUniformBufferSize = Constants.alignedEnvironmentUniformSize * maxInFlightFrames
// Create and allocate our uniform buffer objects. Indicate shared storage so that both the
// CPU can access the buffer
materialUniformBuffer = device?.makeBuffer(length: materialUniformBufferSize, options: .storageModeShared)
materialUniformBuffer?.label = "Material Uniform Buffer"
jointTransformBuffer = device?.makeBuffer(length: jointTransformBufferSize, options: [])
jointTransformBuffer?.label = "Joint Transform Buffer"
effectsUniformBuffer = device?.makeBuffer(length: effectsUniformBufferSize, options: .storageModeShared)
effectsUniformBuffer?.label = "Effects Uniform Buffer"
environmentUniformBuffer = device?.makeBuffer(length: environmentUniformBufferSize, options: .storageModeShared)
environmentUniformBuffer?.label = "Environment Uniform Buffer"
geometricEntities = []
}
func loadAssets(forGeometricEntities theGeometricEntities: [AKGeometricEntity], fromModelProvider modelProvider: ModelProvider?, textureLoader aTextureLoader: MTKTextureLoader, completion: (() -> Void)) {
guard let modelProvider = modelProvider else {
print("Serious Error - Model Provider not found.")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelProviderNotFound, userInfo: nil)
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
completion()
return
}
textureLoader = aTextureLoader
geometricEntities.append(contentsOf: theGeometricEntities)
//
// Create and load our models
//
var numModels = theGeometricEntities.count
// Load the default model
modelProvider.loadAsset(forObjectType: "AnyAnchor", identifier: nil) { [weak self] asset in
guard let asset = asset else {
print("Warning (AnchorsRenderModule) - Failed to get a MDLAsset for type \"AnyAnchor\") from the modelProvider. Aborting the render phase.")
let newError = AKError.warning(.modelError(.modelNotFound(ModelErrorInfo(type: "AnyAnchor"))))
recordNewError(newError)
completion()
return
}
self?.modelAssetsByUUID[generalUUID] = asset
if numModels == 0 {
completion()
}
}
// Load the per-geometry models
for geometricEntity in theGeometricEntities {
if let identifier = geometricEntity.identifier {
modelProvider.loadAsset(forObjectType: "AnyAnchor", identifier: identifier) { [weak self] asset in
guard let asset = asset else {
print("Warning (AnchorsRenderModule) - Failed to get a MDLAsset for type \"AnyAnchor\") with identifier \(identifier) from the modelProvider. Aborting the render phase.")
let newError = AKError.warning(.modelError(.modelNotFound(ModelErrorInfo(type: "AnyAnchor", identifier: identifier))))
recordNewError(newError)
completion()
return
}
self?.modelAssetsByUUID[identifier] = asset
self?.shaderPreferenceByUUID[identifier] = geometricEntity.shaderPreference
}
}
numModels -= 1
if numModels <= 0 {
completion()
}
}
}
func loadPipeline(withModuleEntities: [AKEntity], metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, modelManager: ModelManager, renderPass: RenderPass? = nil, numQualityLevels: Int = 1, completion: (([DrawCallGroup]) -> Void)? = nil) {
guard let device = device else {
print("Serious Error - device not found")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeDeviceNotFound, userInfo: nil)
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
state = .uninitialized
completion?([])
return
}
// Make sure there is at least one general purpose model
guard modelAssetsByUUID[generalUUID] != nil else {
print("Warning (AnchorsRenderModule) - Anchor Model was not found. Aborting the render phase.")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelNotFound, userInfo: nil)
let newError = AKError.warning(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
state = .ready
completion?([])
return
}
var drawCallGroups = [DrawCallGroup]()
// Get a list of uuids
let filteredGeometryUUIDs = geometricEntities.compactMap({$0.identifier})
// filter the `modelAssetsByUUID` by the model asses contained in the list of uuids
let filteredModelsByUUID = modelAssetsByUUID.filter { (uuid, asset) in
filteredGeometryUUIDs.contains(uuid)
}
let total = filteredModelsByUUID.count
var count = 0
// Create a draw call group for every model asset. Each model asset may have multiple instances.
for item in filteredModelsByUUID {
guard let geometricEntity = geometricEntities.first(where: {$0.identifier == item.key}) else {
continue
}
let uuid = item.key
let mdlAsset = item.value
let shaderPreference: ShaderPreference = {
if let prefernece = shaderPreferenceByUUID[uuid] {
return prefernece
} else {
return .pbr
}
}()
modelManager.meshGPUData(for: mdlAsset, shaderPreference: shaderPreference) { [weak self] (meshGPUData, cacheKey) in
// Create a draw call group that contins all of the individual draw calls for this model
if let meshGPUData = meshGPUData, let drawCallGroup = self?.createDrawCallGroup(forUUID: uuid, withMetalLibrary: metalLibrary, renderDestination: renderDestination, renderPass: renderPass, meshGPUData: meshGPUData, geometricEntity: geometricEntity, numQualityLevels: numQualityLevels) {
drawCallGroup.moduleIdentifier = AnchorsRenderModule.identifier
drawCallGroups.append(drawCallGroup)
}
count += 1
if count == total {
// Because there must be a deterministic way to order the draw calls so the draw call groups are sorted by UUID.
drawCallGroups.sort { $0.uuid.uuidString < $1.uuid.uuidString }
self?.state = .ready
completion?(drawCallGroups)
}
}
}
}
//
// Per Frame Updates
//
func updateBufferState(withBufferIndex theBufferIndex: Int) {
bufferIndex = theBufferIndex
materialUniformBufferOffset = RenderModuleConstants.alignedMaterialSize * bufferIndex
jointTransformBufferOffset = Constants.alignedJointTransform * Constants.maxJointCount * bufferIndex
effectsUniformBufferOffset = Constants.alignedEffectsUniformSize * bufferIndex
environmentUniformBufferOffset = Constants.alignedEnvironmentUniformSize * bufferIndex
materialUniformBufferAddress = materialUniformBuffer?.contents().advanced(by: materialUniformBufferOffset)
jointTransformBufferAddress = jointTransformBuffer?.contents().advanced(by: jointTransformBufferOffset)
effectsUniformBufferAddress = effectsUniformBuffer?.contents().advanced(by: effectsUniformBufferOffset)
environmentUniformBufferAddress = environmentUniformBuffer?.contents().advanced(by: environmentUniformBufferOffset)
}
func updateBuffers(withModuleEntities moduleEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, argumentBufferProperties theArgumentBufferProperties: ArgumentBufferProperties, forRenderPass renderPass: RenderPass) {
argumentBufferProperties = theArgumentBufferProperties
let anchors: [AKAugmentedAnchor] = moduleEntities.compactMap({
if let anAnchor = $0 as? AKAugmentedAnchor {
return anAnchor
} else {
return nil
}
})
// Update the anchor uniform buffer with transforms of the current frame's anchors
anchorInstanceCount = 0
var anchorsByUUID = [UUID: [AKAugmentedAnchor]]()
environmentTextureByUUID = [:]
//
// Gather the UUID's
//
for akAnchor in anchors {
guard let arAnchor = akAnchor.arAnchor else {
continue
}
// Ignore anchors that are beyond the renderDistance
let distance = anchorDistance(withTransform: arAnchor.transform, cameraProperties: cameraProperties)
guard Double(distance) < renderDistance else {
continue
}
anchorInstanceCount += 1
if anchorInstanceCount > Constants.maxAnchorInstanceCount {
anchorInstanceCount = Constants.maxAnchorInstanceCount
break
}
// If an anchor is passed in that does not seem to be associated with any model, assign it the `generalUUD` so it will be rendered with a general model
let uuid: UUID = {
if modelAssetsByUUID[arAnchor.identifier] != nil {
return arAnchor.identifier
} else {
return generalUUID
}
}()
// collect all of the anchors by uuid. A uuid can be associated with multiple anchors (like the general uuid).
if let currentAnchors = anchorsByUUID[uuid] {
var mutableCurrentAnchors = currentAnchors
mutableCurrentAnchors.append(akAnchor)
anchorsByUUID[uuid] = mutableCurrentAnchors
} else {
anchorsByUUID[uuid] = [akAnchor]
}
// See if this anchor is associated with an environment anchor. An environment anchor applies to a region of space which may contain several anchors. The environment anchor that has the smallest volume is assumed to be more localized and therefore be the best for for this anchor
let environmentProbes: [AREnvironmentProbeAnchor] = environmentProperties.environmentAnchorsWithReatedAnchors.compactMap{
if $0.value.contains(arAnchor.identifier) {
return $0.key
} else {
return nil
}
}
if environmentProbes.count > 1 {
var bestEnvironmentProbe: AREnvironmentProbeAnchor?
environmentProbes.forEach {
if let theBestEnvironmentProbe = bestEnvironmentProbe {
let existingVolume = AKCube(position: AKVector(x: theBestEnvironmentProbe.transform.columns.3.x, y: theBestEnvironmentProbe.transform.columns.3.y, z: theBestEnvironmentProbe.transform.columns.3.z), extent: AKVector(theBestEnvironmentProbe.extent)).volume()
let newVolume = AKCube(position: AKVector(x: $0.transform.columns.3.x, y: $0.transform.columns.3.y, z: $0.transform.columns.3.z), extent: AKVector($0.extent)).volume()
if newVolume < existingVolume {
bestEnvironmentProbe = $0
}
} else {
bestEnvironmentProbe = $0
}
}
if let environmentProbeAnchor = bestEnvironmentProbe, let texture = environmentProbeAnchor.environmentTexture {
environmentTextureByUUID[uuid] = texture
}
} else {
if let environmentProbeAnchor = environmentProbes.first, let texture = environmentProbeAnchor.environmentTexture {
environmentTextureByUUID[uuid] = texture
}
}
}
//
// Update Textures
//
//
// Update the Buffers
//
var anchorMeshIndex = 0
for drawCallGroup in renderPass.drawCallGroups {
let uuid = drawCallGroup.uuid
for drawCall in drawCallGroup.drawCalls {
let akAnchors = anchorsByUUID[uuid] ?? []
anchorCountByUUID[uuid] = akAnchors.count
guard let drawData = drawCall.drawData else {
continue
}
for akAnchor in akAnchors {
//
// Update skeletons
//
updateSkeletonAnimation(from: drawData, frameNumber: cameraProperties.currentFrame, frameRate: cameraProperties.frameRate)
//
// Update Environment
//
environmentData = {
var myEnvironmentData = EnvironmentData()
if let texture = environmentTextureByUUID[uuid] {
myEnvironmentData.environmentTexture = texture
myEnvironmentData.hasEnvironmentMap = true
return myEnvironmentData
} else {
myEnvironmentData.hasEnvironmentMap = false
}
return myEnvironmentData
}()
let environmentUniforms = environmentUniformBufferAddress?.assumingMemoryBound(to: EnvironmentUniforms.self).advanced(by: anchorMeshIndex)
// Set up lighting for the scene using the ambient intensity if provided
let ambientIntensity: Float = {
if let lightEstimate = environmentProperties.lightEstimate {
return Float(lightEstimate.ambientIntensity) / 1000.0
} else {
return 1
}
}()
let ambientLightColor: SIMD3<Float> = {
if let lightEstimate = environmentProperties.lightEstimate {
return getRGB(from: lightEstimate.ambientColorTemperature)
} else {
return SIMD3<Float>(0.5, 0.5, 0.5)
}
}()
environmentUniforms?.pointee.ambientLightIntensity = ambientIntensity
environmentUniforms?.pointee.ambientLightColor = ambientLightColor// * ambientIntensity
var directionalLightDirection : SIMD3<Float> = environmentProperties.directionalLightDirection
directionalLightDirection = simd_normalize(directionalLightDirection)
environmentUniforms?.pointee.directionalLightDirection = directionalLightDirection
let directionalLightColor: SIMD3<Float> = SIMD3<Float>(0.6, 0.6, 0.6)
environmentUniforms?.pointee.directionalLightColor = directionalLightColor// * ambientIntensity
environmentUniforms?.pointee.directionalLightMVP = environmentProperties.directionalLightMVP
environmentUniforms?.pointee.shadowMVPTransformMatrix = shadowProperties.shadowMVPTransformMatrix
if environmentData?.hasEnvironmentMap == true {
environmentUniforms?.pointee.hasEnvironmentMap = 1
} else {
environmentUniforms?.pointee.hasEnvironmentMap = 0
}
//
// Update Effects uniform
//
let effectsUniforms = effectsUniformBufferAddress?.assumingMemoryBound(to: AnchorEffectsUniforms.self).advanced(by: anchorMeshIndex)
var hasSetAlpha = false
var hasSetGlow = false
var hasSetTint = false
var hasSetScale = false
if let effects = akAnchor.effects {
let currentTime: TimeInterval = Double(cameraProperties.currentFrame) / cameraProperties.frameRate
for effect in effects {
switch effect.effectType {
case .alpha:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniforms?.pointee.alpha = value
hasSetAlpha = true
}
case .glow:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniforms?.pointee.glow = value
hasSetGlow = true
}
case .tint:
if let value = effect.value(forTime: currentTime) as? SIMD3<Float> {
effectsUniforms?.pointee.tint = value
hasSetTint = true
}
case .scale:
if let value = effect.value(forTime: currentTime) as? Float {
let scaleMatrix = matrix_identity_float4x4
effectsUniforms?.pointee.scale = scaleMatrix.scale(x: value, y: value, z: value)
hasSetScale = true
}
}
}
}
if !hasSetAlpha {
effectsUniforms?.pointee.alpha = 1
}
if !hasSetGlow {
effectsUniforms?.pointee.glow = 0
}
if !hasSetTint {
effectsUniforms?.pointee.tint = SIMD3<Float>(1,1,1)
}
if !hasSetScale {
effectsUniforms?.pointee.scale = matrix_identity_float4x4
}
anchorMeshIndex += 1
}
}
}
//
// Update the shadow map
//
shadowMap = shadowProperties.shadowMap
}
func draw(withRenderPass renderPass: RenderPass, sharedModules: [SharedRenderModule]?) {
guard anchorInstanceCount > 0 else {
return
}
guard let renderEncoder = renderPass.renderCommandEncoder else {
return
}
// Push a debug group allowing us to identify render commands in the GPU Frame Capture tool
renderEncoder.pushDebugGroup("Draw Anchors")
if let argumentBufferProperties = argumentBufferProperties, let vertexArgumentBuffer = argumentBufferProperties.vertexArgumentBuffer {
renderEncoder.pushDebugGroup("Argument Buffer")
renderEncoder.setVertexBuffer(vertexArgumentBuffer, offset: argumentBufferProperties.vertexArgumentBufferOffset(forFrame: bufferIndex), index: Int(kBufferIndexPrecalculationOutputBuffer.rawValue))
renderEncoder.popDebugGroup()
}
if let environmentUniformBuffer = environmentUniformBuffer, renderPass.usesEnvironment {
renderEncoder.pushDebugGroup("Draw Environment Uniforms")
if let environmentTexture = environmentData?.environmentTexture, environmentData?.hasEnvironmentMap == true {
renderEncoder.setFragmentTexture(environmentTexture, index: Int(kTextureIndexEnvironmentMap.rawValue))
}
renderEncoder.setFragmentBuffer(environmentUniformBuffer, offset: environmentUniformBufferOffset, index: Int(kBufferIndexEnvironmentUniforms.rawValue))
renderEncoder.popDebugGroup()
}
if let effectsBuffer = effectsUniformBuffer, renderPass.usesEffects {
renderEncoder.pushDebugGroup("Draw Effects Uniforms")
renderEncoder.setFragmentBuffer(effectsBuffer, offset: effectsUniformBufferOffset, index: Int(kBufferIndexAnchorEffectsUniforms.rawValue))
renderEncoder.popDebugGroup()
}
if let shadowMap = shadowMap, renderPass.usesShadows {
renderEncoder.pushDebugGroup("Attach Shadow Buffer")
renderEncoder.setFragmentTexture(shadowMap, index: Int(kTextureIndexShadowMap.rawValue))
renderEncoder.popDebugGroup()
}
var drawCallGroupIndex: Int32 = 0
var drawCallIndex: Int32 = 0
var baseIndex = 0
for drawCallGroup in renderPass.drawCallGroups {
guard drawCallGroup.moduleIdentifier == moduleIdentifier else {
drawCallIndex += Int32(drawCallGroup.drawCalls.count)
drawCallGroupIndex += 1
continue
}
// Use the render pass filter function to skip draw call groups on an individual basis
if let filterFunction = renderPass.drawCallGroupFilterFunction {
guard filterFunction(drawCallGroup) else {
drawCallIndex += Int32(drawCallGroup.drawCalls.count)
drawCallGroupIndex += 1
continue
}
}
let uuid = drawCallGroup.uuid
// TODO: remove. I think this should always be 1. Even if draw call groups share geometries, we should only be incrementing the base index once per draw call. The whole idea of sharing geometries is probably misguided anyway
let anchorcount = (anchorCountByUUID[uuid] ?? 0)
if anchorcount > 1 {
print("There are \(anchorcount) geometries sharing this one UUID. This is something to refactor.")
}
// Geometry Draw Calls. The order of the draw calls in the draw call group determines the order in which they are dispatched to the GPU for rendering.
for drawCall in drawCallGroup.drawCalls {
guard let drawData = drawCall.drawData else {
drawCallIndex += 1
continue
}
drawCall.prepareDrawCall(withRenderPass: renderPass)
if renderPass.usesGeometry {
// Set the offset index of the draw call into the argument buffer
renderEncoder.setVertexBytes(&drawCallIndex, length: MemoryLayout<Int32>.size, index: Int(kBufferIndexDrawCallIndex.rawValue))
// Set the offset index of the draw call group into the argument buffer
renderEncoder.setVertexBytes(&drawCallGroupIndex, length: MemoryLayout<Int32>.size, index: Int(kBufferIndexDrawCallGroupIndex.rawValue))
if renderPass.hasSkeleton {
// Set any buffers fed into our render pipeline
renderEncoder.setVertexBuffer(jointTransformBuffer, offset: jointTransformBufferOffset, index: Int(kBufferIndexMeshJointTransforms.rawValue))
}
}
var mutableDrawData = drawData
mutableDrawData.instanceCount = anchorcount
// Set the mesh's vertex data buffers and draw
draw(withDrawData: mutableDrawData, with: renderEncoder, baseIndex: baseIndex, includeGeometry: renderPass.usesGeometry, includeSkeleton: renderPass.hasSkeleton, includeLighting: renderPass.usesLighting)
baseIndex += anchorcount
drawCallIndex += 1
}
drawCallGroupIndex += 1
}
renderEncoder.popDebugGroup()
}
func frameEncodingComplete(renderPasses: [RenderPass]) {
// Here it is safe to update textures
guard let renderPass = renderPasses.first(where: {$0.name == "Main Render Pass"}) else {
return
}
for drawCallGroup in renderPass.drawCallGroups {
let uuid = drawCallGroup.uuid
for drawCall in drawCallGroup.drawCalls {
guard let drawData = drawCall.drawData else {
continue
}
guard let akAnchor = geometricEntities.first(where: {$0 is AKAugmentedAnchor && $0.identifier == uuid}) else {
continue
}
//
// Update Base Color texture
//
// Currently only supports AugmentedUIViewSurface's with a single submesh
if let viewSurface = akAnchor as? AugmentedUIViewSurface, viewSurface.needsColorTextureUpdate, let baseColorTexture = drawData.subData[0].baseColorTexture, drawData.subData.count == 1 {
DispatchQueue.main.sync {
viewSurface.updateTextureWithCurrentPixelData(baseColorTexture)
}
}
}
}
}
//
// Util
//
func recordNewError(_ akError: AKError) {
errors.append(akError)
}
// MARK: - Private
private enum Constants {
static let maxAnchorInstanceCount = 256
static let maxJointCount = 100
static let alignedJointTransform = (MemoryLayout<matrix_float4x4>.stride & ~0xFF) + 0x100
static let alignedEffectsUniformSize = ((MemoryLayout<AnchorEffectsUniforms>.stride * Constants.maxAnchorInstanceCount) & ~0xFF) + 0x100
static let alignedEnvironmentUniformSize = ((MemoryLayout<EnvironmentUniforms>.stride * Constants.maxAnchorInstanceCount) & ~0xFF) + 0x100
}
private var bufferIndex: Int = 0
private var device: MTLDevice?
private var textureLoader: MTKTextureLoader?
private var geometricEntities = [AKGeometricEntity]()
private var generalUUID = UUID()
private var modelAssetsByUUID = [UUID: MDLAsset]()
private var shaderPreferenceByUUID = [UUID: ShaderPreference]()
private var materialUniformBuffer: MTLBuffer?
private var jointTransformBuffer: MTLBuffer?
private var effectsUniformBuffer: MTLBuffer?
private var environmentUniformBuffer: MTLBuffer?
private var environmentData: EnvironmentData?
private var shadowMap: MTLTexture?
private var argumentBufferProperties: ArgumentBufferProperties?
// Offset within materialUniformBuffer to set for the current frame
private var materialUniformBufferOffset: Int = 0
// Offset within jointTransformBuffer to set for the current frame
private var jointTransformBufferOffset = 0
// Offset within effectsUniformBuffer to set for the current frame
private var effectsUniformBufferOffset: Int = 0
// Offset within environmentUniformBuffer to set for the current frame
private var environmentUniformBufferOffset: Int = 0
// Addresses to write anchor uniforms to each frame
private var materialUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write jointTransform to each frame
private var jointTransformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write effects uniforms to each frame
private var effectsUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write environment uniforms to each frame
private var environmentUniformBufferAddress: UnsafeMutableRawPointer?
// number of frames in the anchor animation by anchor index
private var anchorAnimationFrameCount = [Int]()
private var anchorCountByUUID = [UUID: Int]()
private var environmentTextureByUUID = [UUID: MTLTexture]()
private func createDrawCallGroup(forUUID uuid: UUID, withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, renderPass: RenderPass?, meshGPUData: MeshGPUData, geometricEntity: AKGeometricEntity, numQualityLevels: Int) -> DrawCallGroup {
guard let renderPass = renderPass else {
print("Warning - Skipping all draw calls because the render pass is nil.")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeRenderPassNotFound, userInfo: nil)
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
return DrawCallGroup(drawCalls: [], uuid: uuid)
}
let shaderPreference = meshGPUData.shaderPreference
// Create a draw call group containing draw calls. Each draw call is associated with a `DrawData` object in the `MeshGPUData`
var drawCalls = [DrawCall]()
for drawData in meshGPUData.drawData {
let fragmentShaderName: String = {
if shaderPreference == .simple {
return "anchorGeometryFragmentLightingSimple"
} else if shaderPreference == .blinn {
return "anchorGeometryFragmentLightingBlinnPhong"
} else {
return "anchorGeometryFragmentLighting"
}
}()
let vertexShaderName: String = {
if drawData.hasSkeleton {
return "anchorGeometryVertexTransformSkinned"
} else {
if drawData.isRaw {
return "rawGeometryVertexTransform"
} else {
return "anchorGeometryVertexTransform"
}
}
}()
// The cull mode is set to from because the x geometry is flipped in the shader
let drawCall = DrawCall(metalLibrary: metalLibrary, renderPass: renderPass, vertexFunctionName: vertexShaderName, fragmentFunctionName: fragmentShaderName, vertexDescriptor: meshGPUData.vertexDescriptor, cullMode: .front, drawData: drawData, numQualityLevels: numQualityLevels)
drawCalls.append(drawCall)
}
let drawCallGroup = DrawCallGroup(drawCalls: drawCalls, uuid: uuid, generatesShadows: geometricEntity.generatesShadows)
return drawCallGroup
}
private func updateSkeletonAnimation(from drawData: DrawData, frameNumber: UInt, frameRate: Double = 60) {
let capacity = Constants.alignedJointTransform * Constants.maxJointCount
let boundJointTransformData = jointTransformBufferAddress?.bindMemory(to: matrix_float4x4.self, capacity: capacity)
let jointTransformData = UnsafeMutableBufferPointer<matrix_float4x4>(start: boundJointTransformData, count: Constants.maxJointCount)
if let skeleton = drawData.skeleton {
let keyTimes = skeleton.animations.map{ $0.keyTime }
let time = (Double(frameNumber) * 1.0 / frameRate)
let keyframeIndex = lowerBoundKeyframeIndex(keyTimes, key: time) ?? 0
let jointTransforms = evaluateJointTransforms(skeletonData: skeleton, keyframeIndex: keyframeIndex)
for k in 0..<jointTransforms.count {
jointTransformData[k] = jointTransforms[k]
}
}
}
}
| mit |
ben-ng/swift | test/SILOptimizer/devirt_base_class.swift | 7 | 1413 | // RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s
public class Base1 { @inline(never) func f() -> Int { return 0 } }
public class Base2: Base1 {
}
private class A: Base2 { }
private class B : A {
@inline(never) override func f() -> Int { return 1 }
}
private class C : A {
@inline(never) override func f() -> Int { return 2 }
}
@inline(never)
private func foo(_ a: A) -> Int {
// Check that a.f() call can be devirtualized, even
// though f is defined by one of the A's superclasses.
//
// CHECK-LABEL: sil private [noinline] @{{.*}}foo
// CHECK-NOT: class_method
// CHECK: checked_cast_br
// CHECK: function_ref
// CHECK: checked_cast_br
// CHECK: function_ref
return a.f()
}
// Check that invocation of addConstraint() gets completely devirtualized and inlined
//
// CHECK-LABEL: sil private [noinline] @{{.*}}_TFC17devirt_base_classP33_C1ED27807F941A622F32D66AB60A15CD2F24test
// CHECK-NOT: class_method
// CHECK-NOT: function_ref
// CHECK: return
print("foo(C()) = \(foo(C()))")
private class F1 {
init() {
}
func addConstraint() {
addToGraph()
}
func addToGraph() {
}
}
private class F2 : F1 {
init (v : Int) {
super.init()
addConstraint()
}
override func addToGraph() {
}
@inline(never)
func test() {
addConstraint()
}
}
private class F3 : F2 {
}
private var f = F2(v:1)
f.test()
print("unary constraint is: \(f)")
| apache-2.0 |
britez/sdk-ios | Example/sdk_ios_v2/ViewController.swift | 1 | 2585 | //
// ViewController.swift
// DEC2_sdk_ios
//
// Created by Ezequiel Apfel on 04/25/2017.
// Copyright (c) 2017 Ezequiel Apfel. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
//MARK: Properties
@IBOutlet weak var cardNumber: UITextField!
@IBOutlet weak var expirationMonth: UITextField!
@IBOutlet weak var expirationYear: UITextField!
@IBOutlet weak var securityCode: UITextField!
@IBOutlet weak var cardHolderName: UITextField!
@IBOutlet weak var docType: UITextField!
@IBOutlet weak var docNumber: UITextField!
@IBOutlet weak var textResult: UILabel!
var paymentTokenApi:PaymentsTokenAPI = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cardNumber.delegate = self
expirationMonth.delegate = self
expirationYear.delegate = self
securityCode.delegate = self
cardHolderName.delegate = self
docType.delegate = self
docNumber.delegate = self
}
@IBAction func proceedPayment(_ sender: UIButton) {
let pti = PaymentTokenInfo()
pti.cardNumber = cardNumber.text
pti.cardExpirationMonth = expirationMonth.text
pti.cardExpirationYear = expirationYear.text
pti.cardHolderName = cardHolderName.text
pti.securityCode = securityCode.text
let holder = CardHolderIdentification()
holder.type = docType.text
holder.number = docNumber.text
pti.cardHolderIdentification = holder
self.paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in
guard error == nil else {
if case let ErrorResponse.Error(_, _, dec as ModelError) = error! {
self.textResult.text = dec.toString()
}
return
}
if let paymentToken = paymentToken {
self.textResult.text = paymentToken.toString()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| mit |
adrfer/swift | test/DebugInfo/for.swift | 1 | 473 | // RUN: %target-swift-frontend -g -emit-ir %s | FileCheck %s
// Verify that variables bound in the for statements are in distinct scopes.
for var i = 0; i < 3; i += 1 {
// CHECK: !DILocalVariable(name: "i", scope: ![[SCOPE1:[0-9]+]]
// CHECK: ![[SCOPE1]] = distinct !DILexicalBlock(scope: ![[MAIN:[0-9]+]]
}
for var i = 0; i < 3; i += 1 {
// CHECK: !DILocalVariable(name: "i", scope: ![[SCOPE2:[0-9]+]]
// CHECK: ![[SCOPE2]] = distinct !DILexicalBlock(scope: ![[MAIN]]
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/27267-swift-genericparamlist-create.swift | 4 | 280 | // RUN: not %target-swift-frontend %s -parse
// 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{{}enum S<S where f:T>:a{class A{func a{struct B{let e=a{
| apache-2.0 |
mentrena/SyncKit | Example/Common/Company/CompanyTableViewCell.swift | 1 | 954 | //
// CompanyTableViewCell.swift
// SyncKitCoreDataExample
//
// Created by Manuel Entrena on 21/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import UIKit
class CompanyTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel?
@IBOutlet weak var shareButton: UIButton?
var viewModel: CompanyCellViewModel? {
didSet {
updateWithViewModel()
}
}
func updateWithViewModel() {
guard let viewModel = viewModel else { return }
nameLabel?.text = viewModel.name
if viewModel.isSharedWithMe {
shareButton?.setTitle("Shared with me", for: .normal)
} else {
shareButton?.setTitle(viewModel.isSharing ? "Sharing" : "Share", for: .normal)
}
shareButton?.isHidden = !viewModel.showShareStatus
}
@IBAction func didTapShare() {
viewModel?.shareAction?()
}
}
| mit |
itsjingun/govhacknz_mates | Mates/Controllers/MTSFindMatesResultViewController.swift | 1 | 3730 | //
// MTSFindMatesResultViewController.swift
// Mates
//
// Created by Jingun Lee on 4/07/15.
//
import UIKit
class MTSFindMatesResultViewController: MTSBaseViewController, UITableViewDelegate, UITableViewDataSource {
var userProfiles: Array<MTSUserProfile>?
// UI Views
@IBOutlet weak var viewLoadingContainer: UIView!
@IBOutlet weak var tableViewUserProfiles: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
loadMates()
}
private func setupViews() {
tableViewUserProfiles.delegate = self
tableViewUserProfiles.dataSource = self
}
private func loadMates() {
let userService = MTSUserService()
// Find matching users asynchronously.
userService.findMatchingUsers(
{(userProfiles: Array<MTSUserProfile>) -> () in // On success
self.userProfiles = userProfiles
self.fadeOutAndHideView(self.viewLoadingContainer, withDuration: 0.5)
self.updateViews()
}, failure: { (code, error) -> () in // On failure
// Show error alert message and pop the view controller.
self.showAlertViewWithTitle("Error", message: error, onComplete: { () -> () in
self.navigationController?.popViewControllerAnimated(true)
})
}
)
}
private func fadeOutAndHideView(view: UIView!, withDuration: NSTimeInterval) {
UIView.animateWithDuration(withDuration, animations: { () -> Void in
view.alpha = 0.0
}, completion: { (Bool) -> Void in
view.hidden = true
})
}
private func updateViews() {
self.tableViewUserProfiles.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let userProfile = userProfiles![indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("userProfileTableViewCell", forIndexPath: indexPath) as? MTSUserProfileTableViewCell
// Set name and age.
cell!.setNameAndAge(userProfile.username, age: userProfile.age)
// Set gender.
cell!.setGender(userProfile.genderString)
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if userProfiles != nil {
return userProfiles!.count
}
return 0
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("mateDetailsSegue", sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get user profile for selected row.
let selectedIndex = self.tableViewUserProfiles.indexPathForSelectedRow()!.row
let userProfile = userProfiles![selectedIndex]
// Set data in destination controller.
if let mateDetailsViewController = segue.destinationViewController as? MTSMateDetailsViewController {
mateDetailsViewController.userProfile = userProfile
}
}
}
| gpl-2.0 |
chenyangcun/SwiftDate | ExampleProject/ExampleProject/ViewController.swift | 2 | 1515 | //
// ViewController.swift
// ExampleProject
//
// Created by Mark Norgren on 5/21/15.
//
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let date = NSDate()
_ = date.toString(format: DateFormat.Custom("YYYY-MM-DD"))
_ = date+1.day
let two_months_ago = date-2.months
print(two_months_ago.toLongDateString())
let date_as_utc = date.toUTC() //UTC 时间
let date_as_beijing = date_as_utc.toTimezone("GMT+0800") //北京时间
print(date_as_utc.toLongTimeString())
print(date_as_beijing?.toLongTimeString())
let d = NSDate()-1.hour
print(d.year)
let date1 = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))
let date2 = NSDate.date(fromString: "2015-07-27", format: DateFormat.Custom("YYYY-MM-DD"))
if date2 > date1 {
// TODO something
print("Hello")
}
let abb = d.toRelativeString(abbreviated: true, maxUnits: 3)
print("data: \(abb)")
//
// let w = NSDate()-1.month
// print("Prev month: \(w)")
//
// var w2 = NSDate().add("month",value:-1)
// print(date)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
KrishMunot/swift | test/IRGen/lazy_globals.swift | 6 | 2104 | // RUN: %target-swift-frontend -parse-as-library -emit-ir -primary-file %s | FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8
// CHECK: @_Tv12lazy_globals1xSi = hidden global %Si zeroinitializer, align 8
// CHECK: @_Tv12lazy_globals1ySi = hidden global %Si zeroinitializer, align 8
// CHECK: @_Tv12lazy_globals1zSi = hidden global %Si zeroinitializer, align 8
// CHECK: define internal void @globalinit_[[T]]_func0() {{.*}} {
// CHECK: entry:
// CHECK: store i64 1, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1xSi, i32 0, i32 0), align 8
// CHECK: store i64 2, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1ySi, i32 0, i32 0), align 8
// CHECK: store i64 3, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1zSi, i32 0, i32 0), align 8
// CHECK: ret void
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1xSi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1xSi to i8*)
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1ySi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1ySi to i8*)
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1zSi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1zSi to i8*)
// CHECK: }
var (x, y, z) = (1, 2, 3)
// CHECK: define hidden i64 @_TF12lazy_globals4getXFT_Si() {{.*}} {
// CHECK: entry:
// CHECK: %0 = call i8* @_TF12lazy_globalsau1xSi()
// CHECK: %1 = bitcast i8* %0 to %Si*
// CHECK: %._value = getelementptr inbounds %Si, %Si* %1, i32 0, i32 0
// CHECK: %2 = load i64, i64* %._value, align 8
// CHECK: ret i64 %2
// CHECK: }
func getX() -> Int { return x }
| apache-2.0 |
qinting513/SwiftNote | swift之Alamofire-SwiftyJONS-Kingfisher/Pods/SwiftyJSON/Source/SwiftyJSON.swift | 30 | 34526 | // SwiftyJSON.swift
//
// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type :Int{
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) {
do {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error?.pointee = aError
}
self.init(NSNull())
}
}
/**
Creates a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(_ string:String) -> JSON {
return string.data(using: String.Encoding.utf8)
.flatMap{ JSON(data: $0) } ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: Any) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: Any](minimumCapacity: jsonDictionary.count)
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// Private type
fileprivate var _type: Type = .null
/// prviate error
fileprivate var _error: NSError? = nil
/// Object in JSON
public var object: Any {
get {
switch self.type {
case .array:
return self.rawArray
case .dictionary:
return self.rawDictionary
case .string:
return self.rawString
case .number:
return self.rawNumber
case .bool:
return self.rawBool
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .bool
self.rawBool = number.boolValue
} else {
_type = .number
self.rawNumber = number
}
case let string as String:
_type = .string
self.rawString = string
case _ as NSNull:
_type = .null
case let array as [JSON]:
_type = .array
self.rawArray = array.map { $0.object }
case let array as [Any]:
_type = .array
self.rawArray = array
case let dictionary as [String : Any]:
_type = .dictionary
self.rawDictionary = dictionary
default:
_type = .unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// JSON type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
public enum JSONIndex:Comparable
{
case array(Int)
case dictionary(DictionaryIndex<String, JSON>)
case null
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool
{
switch (lhs, rhs)
{
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
case (.null, .null): return true
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool
{
switch (lhs, rhs)
{
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
extension JSON: Collection
{
public typealias Index = JSONIndex
public var startIndex: Index
{
switch type
{
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(dictionaryValue.startIndex)
default:
return .null
}
}
public var endIndex: Index
{
switch type
{
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(dictionaryValue.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index
{
switch i
{
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(dictionaryValue.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON)
{
switch position
{
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
return dictionaryValue[idx]
default:
return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey
{
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey:JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
let array = elements
self.init(dictionaryLiteral: array)
}
public init(dictionaryLiteral elements: [(String, Any)]) {
let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in
let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in
if let value = dictionary[key] {
return (key, value)
}
return nil
}
return JSON(dictionaryLiteral: initializeElement)
}
var dict = [String : Any](minimumCapacity: elements.count)
for element in elements {
let elementToSet: Any
if let json = element.1 as? JSON {
elementToSet = json.object
} else if let jsonArray = element.1 as? [JSON] {
elementToSet = JSON(jsonArray).object
} else if let dictionary = element.1 as? [String : Any] {
elementToSet = jsonFromDictionaryLiteral(dictionary).object
} else if let dictArray = element.1 as? [[String : Any]] {
let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) }
elementToSet = JSON(jsonArray).object
} else {
elementToSet = element.1
}
dict[element.0] = elementToSet
}
self.init(dict)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements as Any)
}
}
extension JSON: Swift.ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self.init(NSNull() as Any)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
switch self.type {
case .array, .dictionary:
do {
let data = try self.rawData(options: opt)
return String(data: data, encoding: encoding)
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawBool.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.prettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .dictionary {
var d = [String : JSON](minimumCapacity: rawDictionary.count)
for (key, value) in rawDictionary {
d[key] = JSON(value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawBool
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = newValue as Bool
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool:
return self.rawBool
case .number:
return self.rawNumber.boolValue
case .string:
return self.rawString.caseInsensitiveCompare("true") == .orderedSame
default:
return false
}
}
set {
self.object = newValue
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .string:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string:newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .string:
return self.object as? String ?? ""
case .number:
return self.rawNumber.stringValue
case .bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .number:
return self.rawNumber
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .string:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber { // indicates parse error
return NSDecimalNumber.zero
}
return decimal
case .number:
return self.object as? NSNumber ?? NSNumber(value: 0)
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return NSNumber(value: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func exists() -> Bool{
if let errorValue = error, errorValue.code == ErrorNotExist ||
errorValue.code == ErrorIndexOutOfBounds ||
errorValue.code == ErrorWrongType {
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: URL? {
get {
switch self.type {
case .string:
if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int?
{
get
{
return self.number?.intValue
}
set
{
if let newValue = newValue
{
self.object = NSNumber(value: newValue)
} else
{
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber == rhs.rawNumber
case (.string, .string):
return lhs.rawString == rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber <= rhs.rawNumber
case (.string, .string):
return lhs.rawString <= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber >= rhs.rawNumber
case (.string, .string):
return lhs.rawString >= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber > rhs.rawNumber
case (.string, .string):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber < rhs.rawNumber
case (.string, .string):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedSame
}
}
func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedAscending
}
}
func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedDescending
}
}
func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedAscending
}
}
| apache-2.0 |
biohazardlover/NintendoEverything | Pods/SwiftSoup/Sources/OrderedSet.swift | 1 | 12571 | //
// OrderedSet.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 12/11/16.
// Copyright © 2016 Nabil Chatbi. All rights reserved.
//
import Foundation
/// An ordered, unique collection of objects.
public class OrderedSet<T: Hashable> {
public typealias Index = Int
fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>()
/**
Inititalizes an empty ordered set.
- returns: An empty ordered set.
*/
public init() { }
deinit {
removeAllObjects()
}
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
- parameter sequence: The sequence to initialize the ordered set with.
- returns: An initialized ordered set with the contents of sequence.
*/
public init<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for object in sequence {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
public required init(arrayLiteral elements: T...) {
for object in elements {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
- parameter object: The object to find the index for.
- returns: The index of the object, or nil if the object is not in the ordered set.
*/
public func index(of object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/**
Appends an object to the end of the ordered set.
- parameter object: The object to be appended.
*/
public func append(_ object: T) {
if let lastIndex = index(of: object) {
remove(object)
insert(object, at: lastIndex)
} else {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Appends a sequence of objects to the end of the ordered set.
- parameter sequence: The sequence of objects to be appended.
*/
public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T {
var gen = sequence.makeIterator()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
- parameter object: The object to be removed.
*/
public func remove(_ object: T) {
if let index = contents[object] {
contents[object] = nil
sequencedContents[index].deallocate(capacity: 1)
sequencedContents.remove(at: index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
}
}
/**
Removes the given objects from the ordered set.
- parameter objects: The objects to be removed.
*/
public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T {
var gen = objects.makeIterator()
while let object: T = gen.next() {
remove(object)
}
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter index: The index of the object to be removed.
*/
public func removeObject(at index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].pointee)
}
/**
Removes all objects in the ordered set.
*/
public func removeAllObjects() {
contents.removeAll()
for sequencedContent in sequencedContents {
sequencedContent.deallocate(capacity: 1)
}
sequencedContents.removeAll()
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
- parameter first: The first object to be swapped.
- parameter second: The second object to be swapped.
*/
public func swapObject(_ first: T, with second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].pointee = second
sequencedContents[secondPosition].pointee = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
- parameter other: The sequence to look for the intersection in.
- returns: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T {
var gen = other.makeIterator()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
- parameter sequence: The sequence to check.
- returns: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter object: The object to be moved
- parameter index: The index that the object should be moved to.
*/
public func moveObject(_ object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position > index ? -1 : 1
var currentIndex = position
while currentIndex != index {
let nextIndex = currentIndex + adjustment
let firstObject = sequencedContents[currentIndex].pointee
let secondObject = sequencedContents[nextIndex].pointee
sequencedContents[currentIndex].pointee = secondObject
sequencedContents[nextIndex].pointee = firstObject
contents[firstObject] = nextIndex
contents[secondObject] = currentIndex
currentIndex += adjustment
}
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
- parameter index: The index of the object to be moved.
- parameter toIndex: The index that the object should be moved to.
*/
public func moveObject(at index: Index, to toIndex: Index) {
if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
- parameter object: The object to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert(_ object: T, at index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in (index..<count-1).reversed() {
swapObject(self[i], with: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
- parameter objects: The objects to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
for object in objects {
if contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.allocate(capacity: 1)
element.initialize(to: object)
sequencedContents.insert(element, at: seqIdx)
contents[object] = seqIdx
addedObjectCount += 1
}
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].pointee] = i
}
}
/// Returns the last object in the set, or `nil` if the set is empty.
public var last: T? {
return sequencedContents.last?.pointee
}
}
extension OrderedSet: ExpressibleByArrayLiteral { }
extension OrderedSet where T: Comparable {}
extension OrderedSet {
public var count: Int {
return contents.count
}
public var isEmpty: Bool {
return count == 0
}
public var first: T? {
guard count > 0 else { return nil }
return sequencedContents[0].pointee
}
public func index(after i: Int) -> Int {
return sequencedContents.index(after: i)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return contents.count
}
public subscript(index: Index) -> T {
get {
return sequencedContents[index].pointee
}
set {
let previousCount = contents.count
contents[sequencedContents[index].pointee] = nil
contents[newValue] = index
// If the count is reduced we used an existing value, and need to sync up sequencedContents
if contents.count == previousCount {
sequencedContents[index].pointee = newValue
} else {
sequencedContents.remove(at: index)
}
}
}
}
extension OrderedSet: Sequence {
public typealias Iterator = OrderedSetGenerator<T>
public func makeIterator() -> Iterator {
return OrderedSetGenerator(set: self)
}
}
public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol {
public typealias Element = T
private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.makeIterator()
}
public mutating func next() -> Element? {
return generator.next()?.pointee
}
}
extension OrderedSetGenerator where T: Comparable {}
public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let joinedSet = lhs
joinedSet.append(contentsOf: rhs)
return joinedSet
}
public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.append(contentsOf: rhs)
}
public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let purgedSet = lhs
purgedSet.remove(rhs)
return purgedSet
}
public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.remove(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs {
if lhs.contents[object] != rhs.contents[object] {
return false
}
}
return true
}
extension OrderedSet: CustomStringConvertible {
public var description: String {
let children = map({ "\($0)" }).joined(separator: ", ")
return "OrderedSet (\(count) object(s)): [\(children)]"
}
}
| mit |
zhuhaow/soca | soca-iOS/Util/PortValidator.swift | 2 | 724 | //
// PortValidator.swift
// soca
//
// Created by Zhuhao Wang on 3/14/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
import XLForm
class PortValidator : NSObject, XLFormValidatorProtocol {
let min, max: Int
init(min: Int, max: Int) {
self.min = min
self.max = max
}
func isValid(row: XLFormRowDescriptor!) -> XLFormValidationStatus! {
if let port = row.value as? Int {
if port > min && port < max {
return XLFormValidationStatus(msg: nil, status: true, rowDescriptor: row)
}
}
return XLFormValidationStatus(msg: "Invalid port number", status: false, rowDescriptor: row)
}
} | mit |
TouchInstinct/LeadKit | TIUIElements/Sources/Helpers/Extensions/UIView+Animate.swift | 1 | 527 | import UIKit
public extension UIView {
func transition(to coefficient: CGFloat) {
UIView.animate(withDuration: 0.2) { [weak self] in
self?.alpha = coefficient
self?.transform = CGAffineTransform(translationX: 0, y: -coefficient*10)
}
}
func scale(to coefficient: CGFloat) {
UIView.animate(withDuration: 0.2){ [weak self] in
self?.alpha = coefficient
self?.transform = CGAffineTransform(scaleX: coefficient, y: coefficient)
}
}
}
| apache-2.0 |
scinfu/SwiftSoup | Sources/OrderedSet.swift | 1 | 12847 | //
// OrderedSet.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 12/11/16.
// Copyright © 2016 Nabil Chatbi. All rights reserved.
//
import Foundation
/// An ordered, unique collection of objects.
public class OrderedSet<T: Hashable> {
public typealias Index = Int
fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>()
/**
Inititalizes an empty ordered set.
- returns: An empty ordered set.
*/
public init() { }
deinit {
removeAllObjects()
}
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
- parameter sequence: The sequence to initialize the ordered set with.
- returns: An initialized ordered set with the contents of sequence.
*/
public init<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for object in sequence {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
public required init(arrayLiteral elements: T...) {
for object in elements {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
- parameter object: The object to find the index for.
- returns: The index of the object, or nil if the object is not in the ordered set.
*/
public func index(of object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/**
Appends an object to the end of the ordered set.
- parameter object: The object to be appended.
*/
public func append(_ object: T) {
if let lastIndex = index(of: object) {
remove(object)
insert(object, at: lastIndex)
} else {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Appends a sequence of objects to the end of the ordered set.
- parameter sequence: The sequence of objects to be appended.
*/
public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T {
var gen = sequence.makeIterator()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
- parameter object: The object to be removed.
*/
public func remove(_ object: T) {
if let index = contents[object] {
contents[object] = nil
#if !swift(>=4.1)
sequencedContents[index].deallocate(capacity: 1)
#else
sequencedContents[index].deallocate()
#endif
sequencedContents.remove(at: index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
}
}
/**
Removes the given objects from the ordered set.
- parameter objects: The objects to be removed.
*/
public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T {
var gen = objects.makeIterator()
while let object: T = gen.next() {
remove(object)
}
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter index: The index of the object to be removed.
*/
public func removeObject(at index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].pointee)
}
/**
Removes all objects in the ordered set.
*/
public func removeAllObjects() {
contents.removeAll()
for sequencedContent in sequencedContents {
#if !swift(>=4.1)
sequencedContent.deallocate(capacity: 1)
#else
sequencedContent.deallocate()
#endif
}
sequencedContents.removeAll()
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
- parameter first: The first object to be swapped.
- parameter second: The second object to be swapped.
*/
public func swapObject(_ first: T, with second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].pointee = second
sequencedContents[secondPosition].pointee = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
- parameter other: The sequence to look for the intersection in.
- returns: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T {
var gen = other.makeIterator()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
- parameter sequence: The sequence to check.
- returns: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter object: The object to be moved
- parameter index: The index that the object should be moved to.
*/
public func moveObject(_ object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position > index ? -1 : 1
var currentIndex = position
while currentIndex != index {
let nextIndex = currentIndex + adjustment
let firstObject = sequencedContents[currentIndex].pointee
let secondObject = sequencedContents[nextIndex].pointee
sequencedContents[currentIndex].pointee = secondObject
sequencedContents[nextIndex].pointee = firstObject
contents[firstObject] = nextIndex
contents[secondObject] = currentIndex
currentIndex += adjustment
}
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
- parameter index: The index of the object to be moved.
- parameter toIndex: The index that the object should be moved to.
*/
public func moveObject(at index: Index, to toIndex: Index) {
if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
- parameter object: The object to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert(_ object: T, at index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in (index..<count-1).reversed() {
swapObject(self[i], with: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
- parameter objects: The objects to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
for object in objects {
if contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.allocate(capacity: 1)
element.initialize(to: object)
sequencedContents.insert(element, at: seqIdx)
contents[object] = seqIdx
addedObjectCount += 1
}
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].pointee] = i
}
}
/// Returns the last object in the set, or `nil` if the set is empty.
public var last: T? {
return sequencedContents.last?.pointee
}
}
extension OrderedSet: ExpressibleByArrayLiteral { }
extension OrderedSet where T: Comparable {}
extension OrderedSet {
public var count: Int {
return contents.count
}
public var isEmpty: Bool {
return count == 0
}
public var first: T? {
guard count > 0 else { return nil }
return sequencedContents[0].pointee
}
public func index(after i: Int) -> Int {
return sequencedContents.index(after: i)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return contents.count
}
public subscript(index: Index) -> T {
get {
return sequencedContents[index].pointee
}
set {
let previousCount = contents.count
contents[sequencedContents[index].pointee] = nil
contents[newValue] = index
// If the count is reduced we used an existing value, and need to sync up sequencedContents
if contents.count == previousCount {
sequencedContents[index].pointee = newValue
} else {
sequencedContents.remove(at: index)
}
}
}
}
extension OrderedSet: Sequence {
public typealias Iterator = OrderedSetGenerator<T>
public func makeIterator() -> Iterator {
return OrderedSetGenerator(set: self)
}
}
public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol {
public typealias Element = T
private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.makeIterator()
}
public mutating func next() -> Element? {
return generator.next()?.pointee
}
}
extension OrderedSetGenerator where T: Comparable {}
public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let joinedSet = lhs
joinedSet.append(contentsOf: rhs)
return joinedSet
}
public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.append(contentsOf: rhs)
}
public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let purgedSet = lhs
purgedSet.remove(rhs)
return purgedSet
}
public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.remove(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs {
if lhs.contents[object] != rhs.contents[object] {
return false
}
}
return true
}
extension OrderedSet: CustomStringConvertible {
public var description: String {
let children = map({ "\($0)" }).joined(separator: ", ")
return "OrderedSet (\(count) object(s)): [\(children)]"
}
}
| mit |
petrmanek/revolver | Sources/PersistentChromosomeType.swift | 1 | 197 |
/**
* Persistent chromosome type is a chromosome type that can be saved and loaded from persistent storage.
*/
public protocol PersistentChromosomeType: ChromosomeType, PersistentType {
}
| mit |
FarmerChina/RedDotView | RedDotView/AppDelegate.swift | 1 | 2175 | //
// AppDelegate.swift
// RedDotView
//
// Created by 宁国通 on 2017/1/20.
// Copyright © 2017年 宁国通. 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:.
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/21682-no-stacktrace.swift | 11 | 359 | // 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 a {
var d = ""
}
d
class a {
struct S {
deinit {
protocol c {
class c {
class c {
class a {
{
}
class A {
let a {
protocol c {
let g = {
func a {
class c {
deinit {
class
case c,
case
| mit |
Tony0822/DouYuZB | DYZB/DYZB/Classes/Main/MainViewController.swift | 1 | 1245 | //
// MainViewController.swift
// DYZB
//
// Created by TonyYang on 2017/6/15.
// Copyright © 2017年 TonyYang. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVC(storyName: "Home")
addChildVC(storyName: "Live")
addChildVC(storyName: "Follow")
addChildVC(storyName: "Profile")
}
private func addChildVC(storyName: String) {
//1.通过storyboard创建控制器
let childVC = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()!
//2.将childVC作为子控制器
addChildViewController(childVC)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
Sharelink/Bahamut | Bahamut/ChatService.swift | 1 | 9847 |
//
// ReplyService.swift
// Bahamut
//
// Created by AlexChow on 15/7/29.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import Foundation
import UIKit
import EVReflection
//MARK:ChatService
let ChatServiceNewMessageEntities = "ChatServiceNewMessageEntities"
let NewCreatedChatModels = "NewCreatedChatModels"
let NewChatModelsCreated = "NewChatModelsCreated"
extension Message
{
func isInvalidData() -> Bool
{
return msgId == nil || shareId == nil || senderId == nil || msgType == nil || chatId == nil || msg == nil || time == nil
}
}
class ChatService:NSNotificationCenter,ServiceProtocol
{
static let messageServiceNewMessageReceived = "ChatServiceNewMessageReceived"
private(set) var chattingShareId:String!
private var chatMessageServerUrl:String!
@objc static var ServiceName:String {return "Chat Service"}
@objc func appStartInit(appName:String) {}
@objc func userLoginInit(userId: String)
{
self.chatMessageServerUrl = BahamutRFKit.sharedInstance.appApiServer
let route = ChicagoRoute()
route.ExtName = "NotificationCenter"
route.CmdName = "UsrNewMsg"
ChicagoClient.sharedInstance.addChicagoObserver(route, observer: self, selector: #selector(ChatService.newMessage(_:)))
let chatServerChangedRoute = ChicagoRoute()
chatServerChangedRoute.ExtName = "NotificationCenter"
route.CmdName = "ChatServerChanged"
ChicagoClient.sharedInstance.addChicagoObserver(chatServerChangedRoute, observer: self, selector: #selector(ChatService.chatServerChanged(_:)))
self.setServiceReady()
self.getMessageFromServer()
}
func userLogout(userId: String) {
ChicagoClient.sharedInstance.removeObserver(self)
}
static let messageListUpdated = "messageListUpdated"
func setChatAtShare(shareId:String)
{
self.chattingShareId = shareId
}
func isChatingAtShare(shareId:String) -> Bool
{
if String.isNullOrEmpty(shareId)
{
return false
}
return shareId == self.chattingShareId
}
func leaveChatRoom()
{
self.chattingShareId = nil
}
func chatServerChanged(a:NSNotification)
{
class ReturnValue:EVObject
{
var chatServerUrl:String!
}
if let userInfo = a.userInfo
{
if let json = userInfo[ChicagoClientReturnJsonValue] as? String
{
let value = ReturnValue(json: json)
if let chatUrl = value.chatServerUrl
{
if String.isNullOrWhiteSpace(chatUrl)
{
self.chatMessageServerUrl = chatUrl
}
}
}
}
}
func newMessage(a:NSNotification)
{
getMessageFromServer()
}
func getMessageFromServer()
{
let req = GetNewMessagesRequest()
req.apiServerUrl = self.chatMessageServerUrl
let client = BahamutRFKit.sharedInstance.getBahamutClient()
client.execute(req) { (result:SLResult<[Message]>) -> Void in
if var msgs = result.returnObject
{
msgs = msgs.filter{!$0.isInvalidData()} //isInvalidData():AlamofireJsonToObject Issue:responseArray will invoke all completeHandler
if msgs.count == 0
{
return
}
self.recevieMessage(msgs)
let dreq = NotifyNewMessagesReceivedRequest()
dreq.apiServerUrl = self.chatMessageServerUrl
client.execute(dreq, callback: { (result:SLResult<EVObject>) -> Void in
})
}
}
}
func getChatModel(chatId:String) -> ChatModel!
{
return getChatModelByEntity(PersistentManager.sharedInstance.getShareChat(chatId))
}
func getChatModelByEntity(entity:ShareChatEntity!) -> ChatModel!
{
if entity == nil{
return nil
}
let uService = ServiceContainer.getService(UserService)
let cm = ChatModel()
cm.shareId = entity.shareId
cm.chatId = entity.chatId
cm.sharelinkers = entity.getUsers()
if cm.sharelinkers.count >= 1{
let user = uService.getUser(cm.sharelinkers.last!)
cm.chatTitle = user?.getNoteName()
cm.chatIcon = user?.avatarId
cm.audienceId = user?.userId
}else{
cm.chatTitle = "chat hub"
}
cm.shareId = entity.shareId
cm.chatEntity = entity
return cm
}
func getChatIdWithAudienceOfShareId(shareId:String,audienceId:String) -> String
{
return "\(shareId)&\(audienceId)"
}
func getMessage(chatId:String,limit:Int = 7,beforeTime:NSDate! = nil) -> [MessageEntity]
{
return PersistentManager.sharedInstance.getMessage(chatId, limit: limit, beforeTime: beforeTime)
}
func saveNewMessage(msgId:String,chatId:String,shareId:String!,type:MessageType,time:NSDate,senderId:String,msgText:String?,data:NSData?) -> MessageEntity!
{
let msgEntity = PersistentManager.sharedInstance.getNewMessage(msgId)
msgEntity.chatId = chatId
msgEntity.type = type.rawValue
msgEntity.time = time
msgEntity.senderId = senderId
msgEntity.shareId = shareId
if type == .Text
{
msgEntity.msgText = msgText ?? ""
}else if type == .Voice
{
msgEntity.msgData = data ?? NSData()
msgEntity.msgText = msgText ?? "0"
}else if type == .Picture
{
msgEntity.msgData = data ?? NSData()
}
PersistentManager.sharedInstance.saveMessageChanges()
return msgEntity
}
func sendMessage(chatId:String,msg:MessageEntity,shareId:String,audienceId:String)
{
let req = SendMessageRequest()
req.apiServerUrl = self.chatMessageServerUrl
req.time = msg.time
req.type = msg.type
req.chatId = chatId
req.message = msg.msgText
req.messageData = msg.msgData
req.audienceId = audienceId
req.shareId = shareId
let client = BahamutRFKit.sharedInstance.getBahamutClient()
client.execute(req) { (result:SLResult<Message>) -> Void in
if result.isSuccess
{
msg.isSend = true
PersistentManager.sharedInstance.saveMessageChanges()
}else
{
msg.sendFailed = NSNumber(bool: true)
}
}
}
private func recevieMessage(msgs:[Message])
{
let uService = ServiceContainer.getService(UserService)
var msgEntities = [MessageEntity]()
var newChatModels = [ChatModel]()
for msg in msgs
{
let me = saveNewMessage(msg.msgId, chatId: msg.chatId,shareId: msg.shareId, type: MessageType(rawValue: msg.msgType)!, time: msg.timeOfDate, senderId: msg.senderId, msgText: msg.msg, data: msg.msgData)
if let ce = PersistentManager.sharedInstance.getShareChat(me.chatId)
{
ce.newMessage = ce.newMessage.integerValue + 1
}else
{
let ce = createChatEntity(msg.chatId, audienceIds: [uService.myUserId,me.senderId], shareId: me.shareId)
ce.newMessage = 1
PersistentManager.sharedInstance.saveMessageChanges()
let model = getChatModelByEntity(ce)
newChatModels.append(model)
}
msgEntities.append(me)
}
PersistentManager.sharedInstance.saveMessageChanges()
self.postNotificationName(ChatService.messageServiceNewMessageReceived, object: self, userInfo: [ChatServiceNewMessageEntities:msgEntities])
if newChatModels.count > 0
{
self.postNotificationName(NewChatModelsCreated, object: self, userInfo: [NewCreatedChatModels:newChatModels])
}
}
func getShareChatHub(shareId:String,shareSenderId:String) -> ShareChatHub
{
let uService = ServiceContainer.getService(UserService)
var shareChats = PersistentManager.sharedInstance.getShareChats(shareId)
if shareChats.count == 0
{
let chatId = getChatIdWithAudienceOfShareId(shareId, audienceId: uService.myUserId)
var audienceIds = [uService.myUserId]
if uService.myUserId != shareSenderId
{
audienceIds.append(shareSenderId)
}
let newSCE = createChatEntity(chatId, audienceIds: audienceIds, shareId: shareId)
shareChats.append(newSCE)
}
let chatModels = shareChats.map{return self.getChatModel($0.chatId)}.filter{$0 != nil}
let sc = ShareChatHub()
for cm in chatModels
{
sc.addChatModel(cm)
}
sc.shareId = shareId
return sc
}
private func createChatEntity(chatId:String,audienceIds:[String],shareId:String) -> ShareChatEntity
{
let newSCE = PersistentManager.sharedInstance.saveNewChat(shareId,chatId: chatId)
for audience in audienceIds
{
newSCE.addUser(audience)
}
PersistentManager.sharedInstance.saveMessageChanges()
return newSCE
}
func getShareNewMessageCount(shareId:String) -> Int
{
let shareChats = PersistentManager.sharedInstance.getShareChats(shareId)
var sum = 0
for sc in shareChats
{
sum = sum + sc.newMessage.integerValue
}
return sum
}
} | mit |
akaralar/siesta | Source/Siesta/EntityCache.swift | 3 | 6134 | //
// EntityCache.swift
// Siesta
//
// Created by Paul on 2015/8/24.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
/**
A strategy for saving entities between runs of the app. Allows apps to:
- launch with the UI in a valid and populated (though possibly stale) state,
- recover from low memory situations with fewer reissued network requests, and
- work offline.
Siesta uses any HTTP request caching provided by the networking layer (e.g. `URLCache`). Why another type of
caching, then? Because `URLCache` has a subtle but significant mismatch with the use cases above:
* The purpose of HTTP caching is to _prevent_ network requests, but what we need is a way to show old data _while
issuing new requests_. This is the real deal-killer.
Additionally, but less crucially:
* HTTP caching is [complex](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html), and was designed around a set of
goals relating to static assets and shared proxy caches — goals that look very different from reinflating Siesta
resources’ in-memory state. It’s difficult to guarantee that `URLCache` interacting with the HTTP spec will
exhibit the behavior we want; the logic involved is far more tangled and brittle than implementing a separate cache.
* Precisely because of the complexity of these rules, APIs frequently disable all caching via headers.
* HTTP caching does not preserve Siesta’s timestamps, which thwarts the staleness logic.
* HTTP caching stores raw responses; storing parsed responses offers the opportunity for faster app launch.
Siesta currently does not include any implementations of `EntityCache`, but a future version will.
- Warning: Siesta calls `EntityCache` methods on a GCD background queue, so your implementation **must be
thread-safe**.
- SeeAlso: `PipelineStage.cacheUsing(_:)`
*/
public protocol EntityCache
{
/**
The type this cache uses to look up cache entries. The structure of keys is entirely up to the cache, and is
opaque to Siesta.
*/
associatedtype Key
/**
Provides the key appropriate to this cache for the given resource.
A cache may opt out of handling the given resource by returning nil.
This method is called for both cache writes _and_ for cache reads. The `resource` therefore may not have
any content. Implementations will almost always examine `resource.url`. (Cache keys should be _at least_ as unique
as URLs except in very unusual circumstances.) Implementations may also want to examine `resource.configuration`,
for example to take authentication into account.
- Note: This method is always called on the **main thread**. However, the key it returns will be passed repeatedly
across threads. Siesta therefore strongly recommends making `Key` a value type, i.e. a struct.
*/
func key(for resource: Resource) -> Key?
/**
Return the entity associated with the given key, or nil if it is not in the cache.
If this method returns an entity, it does _not_ pass through the transformer pipeline. Implementations should
return the entity as if already fully parsed and transformed — with the same type of `entity.content` that was
originally sent to `writeEntity(...)`.
- Warning: This method may be called on a background thread. Make sure your implementation is threadsafe.
*/
func readEntity(forKey key: Key) -> Entity<Any>?
/**
Store the given entity in the cache, associated with the given key. The key’s format is arbitrary, and internal
to Siesta. (OK, it’s just the resource’s URL, but you should pretend you don’t know that in your implementation.
Cache implementations should treat the `forKey` parameter as an opaque value.)
This method receives entities _after_ they have been through the transformer pipeline. The `entity.content` will
be a parsed object, not raw data.
Implementations are under no obligation to actually perform the write. This method can — and should — examine the
type of the entity’s `content` and/or its header values, and ignore it if it is not encodable.
Note that this method does not receive a URL as input; if you need to limit caching to specific resources, use
Siesta’s configuration mechanism to control which resources are cacheable.
- Warning: The method may be called on a background thread. Make sure your implementation is threadsafe.
*/
func writeEntity(_ entity: Entity<Any>, forKey key: Key)
/**
Update the timestamp of the entity for the given key. If there is no such cache entry, do nothing.
*/
func updateEntityTimestamp(_ timestamp: TimeInterval, forKey key: Key)
/**
Remove any entities cached for the given key. After a call to `removeEntity(forKey:)`, subsequent calls to
`readEntity(forKey:)` for the same key **must** return nil until the next call to `writeEntity(_:forKey:)`.
*/
func removeEntity(forKey key: Key)
/**
Returns the GCD queue on which this cache implementation will do its work.
*/
var workQueue: DispatchQueue { get }
}
internal var defaultEntityCacheWorkQueue: DispatchQueue =
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated)
public extension EntityCache
{
/// Returns a concurrent queue with priority `QOS_CLASS_USER_INITIATED`.
public var workQueue: DispatchQueue
{ return defaultEntityCacheWorkQueue }
}
extension EntityCache
{
/**
Reads the entity from the cache, updates its timestamp, then writes it back.
While this default implementation always gives the correct behavior, cache implementations may choose to override
it for performance reasons.
*/
public func updateEntityTimestamp(_ timestamp: TimeInterval, forKey key: Key)
{
guard var entity = readEntity(forKey: key) else
{ return }
entity.timestamp = timestamp
writeEntity(entity, forKey: key)
}
}
| mit |
icecrystal23/ios-charts | Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift | 3 | 1411 | //
// ILineRadarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc
public protocol ILineRadarChartDataSet: ILineScatterCandleRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
var fillColor: NSUIColor { get set }
/// - returns: The object that is used for filling the area below the line.
/// **default**: nil
var fill: Fill? { get set }
/// The alpha value that is used for filling the line surface.
/// **default**: 0.33
var fillAlpha: CGFloat { get set }
/// line width of the chart (min = 0.0, max = 10)
///
/// **default**: 1
var lineWidth: CGFloat { get set }
/// Set to `true` if the DataSet should be drawn filled (surface), and not just as a line.
/// Disabling this will give great performance boost.
/// Please note that this method uses the path clipping for drawing the filled area (with images, gradients and layers).
var drawFilledEnabled: Bool { get set }
/// - returns: `true` if filled drawing is enabled, `false` if not
var isDrawFilledEnabled: Bool { get }
}
| apache-2.0 |
nheagy/WordPress-iOS | WordPress/Classes/Utility/ImmuTable+WordPress.swift | 1 | 1894 | import WordPressShared
/*
Until https://github.com/wordpress-mobile/WordPress-iOS/pull/4591 is fixed, we
need to use the custom WPTableViewSectionHeaderFooterView.
This lives as an extension on a separate file because it's specific to our UI
implementation and shouldn't be in a generic ImmuTable that we might eventually
release as a standalone library.
*/
extension ImmuTableViewHandler {
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let title = self.tableView(tableView, titleForHeaderInSection: section) {
return WPTableViewSectionHeaderFooterView.heightForHeader(title, width: tableView.frame.width)
} else {
return UITableViewAutomaticDimension
}
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let title = self.tableView(tableView, titleForHeaderInSection: section) else {
return nil
}
let view = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Header)
view.title = title
return view
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let title = self.tableView(tableView, titleForFooterInSection: section) {
return WPTableViewSectionHeaderFooterView.heightForFooter(title, width: tableView.frame.width)
} else {
return UITableViewAutomaticDimension
}
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let title = self.tableView(tableView, titleForFooterInSection: section) else {
return nil
}
let view = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer)
view.title = title
return view
}
}
| gpl-2.0 |
DavidSkrundz/Lua | Sources/Lua/Value/Value.swift | 1 | 2274 | //
// Value.swift
// Lua
//
/// Represents a Lua value that can be converted to a Swift value
///
/// Includes:
/// - `Int`
/// - `UInt32`
/// - `Double`
/// - `String`
/// - `Nil`
/// - `Number`
/// - `Table`
/// - `Function`
/// - `UserData`
/// - `UnsafeMutableRawPointer`
public protocol Value {
var hashValue: Int { get }
}
extension Int: Value {}
extension UInt32: Value {}
extension Double: Value {}
extension String: Value {}
extension Nil: Value {}
extension Number: Value {}
extension Table: Value {}
extension Function: Value {}
extension UserData: Value {}
extension UnsafeMutableRawPointer: Value {}
public func equal(_ lhs: Value, _ rhs: Value) -> Bool {
switch (lhs, rhs) {
case is (Int, Int): return (lhs as! Int) == (rhs as! Int)
case is (UInt32, UInt32): return (lhs as! UInt32) == (rhs as! UInt32)
case is (Double, Double): return (lhs as! Double) == (rhs as! Double)
case is (String, String): return (lhs as! String) == (rhs as! String)
case is (Number, Number): return (lhs as! Number) == (rhs as! Number)
case is (Table, Table): return (lhs as! Table) == (rhs as! Table)
case is (Function, Function): return (lhs as! Function) == (rhs as! Function)
case is (UserData, UserData): return (lhs as! UserData) == (rhs as! UserData)
case is (UnsafeMutableRawPointer, UnsafeMutableRawPointer):
return (lhs as! UnsafeMutableRawPointer) == (rhs as! UnsafeMutableRawPointer)
case is (Int, Number): return (lhs as! Int) == (rhs as! Number).intValue
case is (UInt32, Number): return (lhs as! UInt32) == (rhs as! Number).uintValue
case is (Double, Number): return (lhs as! Double) == (rhs as! Number).doubleValue
case is (Number, Int): return (lhs as! Number).intValue == (rhs as! Int)
case is (Number, UInt32): return (lhs as! Number).uintValue == (rhs as! UInt32)
case is (Number, Double): return (lhs as! Number).doubleValue == (rhs as! Double)
default: return false
}
}
public func ==(lhs: [Value], rhs: [Value]) -> Bool {
if lhs.count != rhs.count { return false }
return zip(lhs, rhs)
.map { equal($0, $1) }
.reduce(true) { $0 && $1 }
}
public func !=(lhs: [Value], rhs: [Value]) -> Bool {
return !(lhs == rhs)
}
| lgpl-3.0 |
ricardrm88/RicRibbonTag | RicRibbonTag/RicRibbonLabel.swift | 1 | 1687 | //
// RicRibbonLabel.swift
//
// MIT License
//
// Copyright (c) 2016 Ricard Romeo Murgó (https://github.com/ricardrm88)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
/// A label which notifies layout updates.
open class RicRibbonLabel: UILabel {
// Delegate used to notify updates.
open var delegate: RicRibbonLabelProtocol!
override open func layoutSubviews() {
super.layoutSubviews()
delegate?.ribbonLabelUpdatedLayout(self)
}
}
/// Protocol for RicRibbonLabel.
public protocol RicRibbonLabelProtocol {
func ribbonLabelUpdatedLayout(_ sender: RicRibbonLabel)
}
| mit |
tskulbru/NBMaterialDialogIOS | Pod/Classes/NBMaterialToast.swift | 2 | 6674 | //
// NBMaterialToast.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// 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.
public enum NBLunchDuration : TimeInterval {
case short = 1.0
case medium = 2.0
case long = 3.5
}
@objc open class NBMaterialToast : UIView {
fileprivate let kHorizontalMargin: CGFloat = 16.0
fileprivate let kVerticalBottomMargin: CGFloat = 16.0
internal let kMinHeight: CGFloat = 48.0
internal let kHorizontalPadding: CGFloat = 24.0
internal let kVerticalPadding: CGFloat = 16.0
internal let kFontRoboto: UIFont = UIFont.robotoRegularOfSize(14)
internal let kFontColor: UIColor = NBConfig.PrimaryTextLight
internal let kDefaultBackground: UIColor = UIColor(hex: 0x323232, alpha: 1.0)
internal var lunchDuration: NBLunchDuration!
internal var hasRoundedCorners: Bool!
internal var constraintViews: [String: AnyObject]!
internal var constraintMetrics: [String: AnyObject]!
override init(frame: CGRect) {
super.init(frame: frame)
lunchDuration = NBLunchDuration.medium
hasRoundedCorners = true
isUserInteractionEnabled = false
backgroundColor = kDefaultBackground
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func __show() {
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1.0
}, completion: { (finished) in
self.__hide()
})
}
internal func __hide() {
UIView.animate(withDuration: 0.8, delay: lunchDuration.rawValue, options: [], animations: {
self.alpha = 0.0
}, completion: { (finished) in
self.removeFromSuperview()
})
}
internal class func __createWithTextAndConstraints(_ windowView: UIView, text: String, duration: NBLunchDuration) -> NBMaterialToast {
let toast = NBMaterialToast()
toast.lunchDuration = duration
toast.alpha = 0.0
toast.translatesAutoresizingMaskIntoConstraints = false
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.clear
textLabel.textAlignment = NSTextAlignment.left
textLabel.font = toast.kFontRoboto
textLabel.textColor = toast.kFontColor
textLabel.numberOfLines = 0
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.text = text
if toast.hasRoundedCorners! {
toast.layer.masksToBounds = true
toast.layer.cornerRadius = 15.0
}
toast.addSubview(textLabel)
windowView.addSubview(toast)
toast.constraintViews = [
"textLabel": textLabel,
"toast": toast
]
toast.constraintMetrics = [
"vPad": toast.kVerticalPadding as AnyObject,
"hPad": toast.kHorizontalPadding as AnyObject,
"minHeight": toast.kMinHeight as AnyObject,
"vMargin": toast.kVerticalBottomMargin as AnyObject,
"hMargin": toast.kHorizontalMargin as AnyObject
]
toast.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPad-[textLabel]-vPad-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews))
toast.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-hPad-[textLabel]-hPad-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews))
toast.setContentHuggingPriority(750, for: UILayoutConstraintAxis.vertical)
toast.setContentHuggingPriority(750, for: UILayoutConstraintAxis.horizontal)
toast.setContentCompressionResistancePriority(750, for: UILayoutConstraintAxis.horizontal)
windowView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[toast(>=minHeight)]-vMargin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews))
windowView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=hMargin)-[toast]-(>=hMargin)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews))
windowView.addConstraint(NSLayoutConstraint(item: toast, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: windowView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
return toast
}
/**
Displays a classic toast message with a user defined text, shown for a standard period of time
- parameter windowView: The window which the toast is to be attached
- parameter text: The message to be displayed
*/
open class func showWithText(_ windowView: UIView, text: String) {
NBMaterialToast.showWithText(windowView, text: text, duration: NBLunchDuration.medium)
}
/**
Displays a classic toast message with a user defined text and duration
- parameter windowView: The window which the toast is to be attached
- parameter text: The message to be displayed
- parameter duration: The duration of the toast
*/
open class func showWithText(_ windowView: UIView, text: String, duration: NBLunchDuration) {
let toast: NBMaterialToast = NBMaterialToast.__createWithTextAndConstraints(windowView, text: text, duration: duration)
toast.__show()
}
}
| mit |
DavidPiper94/MetaheuristicKit | Example/MetaheuristicKit/AppDelegate.swift | 1 | 2157 | //
// AppDelegate.swift
// MetaheuristicKit
//
// Created by DavidPiper94 on 04/19/2016.
// Copyright (c) 2016 DavidPiper94. 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 |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Search/Query/Auxiliary/AroundRadius.swift | 1 | 1245 | //
// AroundRadius.swift
//
//
// Created by Vladislav Fitc on 20/03/2020.
//
import Foundation
/**
Define the maximum radius for a geo search (in meters).
- This setting only works within the context of a radial (circular) geo search, enabled by aroundLatLngViaIP or aroundLatLng.
*/
public enum AroundRadius: Codable, Equatable, URLEncodable {
/**
Disables the radius logic, allowing all results to be returned, regardless of distance.
Ranking is still based on proximity to the central axis point. This option is faster than specifying a high integer value.
*/
case all
/**
Integer value (in meters) representing the radius around the coordinates specified during the query.
*/
case meters(Int)
case other(String)
}
extension AroundRadius: RawRepresentable {
public var rawValue: String {
switch self {
case .all:
return "all"
case .meters(let meters):
return "\(meters)"
case .other(let rawValue):
return rawValue
}
}
public init(rawValue: String) {
switch rawValue {
case AroundRadius.all.rawValue:
self = .all
case _ where Int(rawValue) != nil:
self = .meters(Int(rawValue)!)
default:
self = .other(rawValue)
}
}
}
| mit |
kickstarter/ios-oss | Library/CreditCard+Utils.swift | 1 | 764 | import Foundation
import KsApi
extension UserCreditCards.CreditCard {
public func expirationDate() -> String {
return self.formatted(dateString: self.formattedExpirationDate)
}
private func formatted(dateString: String) -> String {
let date = self.toDate(dateString: dateString)
return Format.date(
secondsInUTC: date.timeIntervalSince1970,
template: "MM-yyyy",
timeZone: UTCTimeZone
)
}
private func toDate(dateString: String) -> Date {
// Always use UTC timezone here this date should be timezone agnostic
guard let date = Format.date(
from: dateString,
dateFormat: "yyyy-MM",
timeZone: UTCTimeZone
) else {
fatalError("Unable to parse date format")
}
return date
}
}
| apache-2.0 |
the-blue-alliance/the-blue-alliance-ios | tba-unit-tests/View Elements/Match/MatchViewModelTests.swift | 1 | 4649 | import TBADataTesting
import XCTest
@testable import TBAData
@testable import The_Blue_Alliance
class MatchViewModelTestCase: TBADataTestCase {
func test_no_breakdown() {
let match = insertMatch(eventKey: "2018inwla")
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 0)
XCTAssertEqual(subject.blueRPCount, 0)
}
func test_bad_bereakdown_keys() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"notThere1": false,
"notThere2": false
],
"blue": [
"notThere1": false,
"notThere2": false
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 0)
XCTAssertEqual(subject.blueRPCount, 0)
}
func test_no_rp() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"autoQuestRankingPoint": false,
"faceTheBossRankingPoint": false
],
"blue": [
"autoQuestRankingPoint": false,
"faceTheBossRankingPoint": false
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 0)
XCTAssertEqual(subject.blueRPCount, 0)
}
func test_first_rp() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": false
],
"blue": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": false
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 1)
XCTAssertEqual(subject.blueRPCount, 1)
}
func test_second_rp() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"autoQuestRankingPoint": false,
"faceTheBossRankingPoint": true
],
"blue": [
"autoQuestRankingPoint": false,
"faceTheBossRankingPoint": true
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 1)
XCTAssertEqual(subject.blueRPCount, 1)
}
func test_both_rp() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": true
],
"blue": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": true
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 2)
XCTAssertEqual(subject.blueRPCount, 2)
}
func test_2018_rp() {
let match = insertMatch(eventKey: "2018inwla")
match.breakdownRaw = [
"red": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": true
],
"blue": [
"autoQuestRankingPoint": true,
"faceTheBossRankingPoint": true
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 2)
XCTAssertEqual(subject.blueRPCount, 2)
}
func test_2017_rp() {
let match = insertMatch(eventKey: "2017inwla")
match.breakdownRaw = [
"red": [
"kPaRankingPointAchieved": true,
"rotorRankingPointAchieved": true
],
"blue": [
"kPaRankingPointAchieved": true,
"rotorRankingPointAchieved": true
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 2)
XCTAssertEqual(subject.blueRPCount, 2)
}
func test_2016_rp() {
let match = insertMatch(eventKey: "2016inwla")
match.breakdownRaw = [
"red": [
"teleopDefensesBreached": true,
"teleopTowerCaptured": true
],
"blue": [
"teleopDefensesBreached": true,
"teleopTowerCaptured": true
]
]
let subject = MatchViewModel(match: match)
XCTAssertEqual(subject.redRPCount, 2)
XCTAssertEqual(subject.blueRPCount, 2)
}
}
| mit |
timd/ProiOSTableCollectionViews | Ch14/WatchTable/WatchTable/AppDelegate.swift | 1 | 2138 | //
// AppDelegate.swift
// WatchTable
//
// Created by Tim on 03/12/15.
// Copyright © 2015 Tim Duckett. 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.