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 |
---|---|---|---|---|---|
svbeemen/Eve | Eve/Eve/Constants.swift | 1 | 330 | //
// Constants.swift
// Eve
//
// Created by Sangeeta van Beemen on 23/06/15.
// Copyright (c) 2015 Sangeeta van Beemen. All rights reserved.
//
import UIKit
let COLUMNS = CGFloat(5)
let MONTHNAMES = ["JANUARY", "FEBURARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"] | mit |
kusl/swift | test/1_stdlib/SpriteKit.swift | 10 | 650 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// watchOS does not have SpriteKit.
// UNSUPPORTED: OS=watchos
import Foundation
import SpriteKit
// SKColor is NSColor on OS X and UIColor on iOS.
var r = CGFloat(0)
var g = CGFloat(0)
var b = CGFloat(0)
var a = CGFloat(0)
var color = SKColor.redColor()
color.getRed(&r, green:&g, blue:&b, alpha:&a)
print("color \(r) \(g) \(b) \(a)")
// CHECK: color 1.0 0.0 0.0 1.0
#if os(OSX)
func f(c: NSColor) {
print("colortastic")
}
#endif
#if os(iOS) || os(tvOS)
func f(c: UIColor) {
print("colortastic")
}
#endif
f(color)
// CHECK: colortastic
| apache-2.0 |
mentrena/SyncKit | Example/Realm/SyncKitRealmExample/SyncKitRealmExample/Employee/Realm/RealmEmployeeWireframe.swift | 1 | 1235 | //
// RealmEmployeeWireframe.swift
// SyncKitRealmSwiftExample
//
// Created by Manuel Entrena on 26/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import UIKit
import Realm
class RealmEmployeeWireframe: EmployeeWireframe {
let navigationController: UINavigationController
let realm: RLMRealm
init(navigationController: UINavigationController, realm: RLMRealm) {
self.navigationController = navigationController
self.realm = realm
}
func show(company: Company, canEdit: Bool) {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Employee") as! EmployeeViewController
let interactor = RealmEmployeeInteractor(realm: realm, company: company)
let presenter = DefaultEmployeePresenter(view: viewController,
company: company,
interactor: interactor,
canEdit: canEdit)
interactor.delegate = presenter
viewController.presenter = presenter
navigationController.pushViewController(viewController, animated: true)
}
}
| mit |
certificate-helper/TLS-Inspector | TLS Inspector/View Controllers/NoticeViewController.swift | 2 | 1248 | import UIKit
class NoticeViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var dismissButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var forgroundColor = UIColor.black
if #available(iOS 13, *) {
forgroundColor = UIColor.label
}
let noticeText = NSMutableAttributedString(string: lang(key:"first_run_notice"),
attributes: [
NSAttributedString.Key.foregroundColor : forgroundColor,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18.0)
])
let foundRange = noticeText.mutableString.range(of: lang(key: "Apple Support"))
noticeText.addAttribute(NSAttributedString.Key.link, value: "https://support.apple.com/", range: foundRange)
noticeText.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 18.0), range: foundRange)
self.textView.attributedText = noticeText
}
@IBAction func dismissButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| gpl-3.0 |
herveperoteau/TracktionProto1 | TracktionProto1/WatchConnectivityManager.swift | 1 | 2586 | //
// WatchConnectivityManager.swift
// TracktionProto1
//
// Created by Hervé PEROTEAU on 03/01/2016.
// Copyright © 2016 Hervé PEROTEAU. All rights reserved.
//
import Foundation
import WatchConnectivity
let NotificationWCsessionWatchStateDidChange = "NotificationWCsessionWatchStateDidChange"
let NotificationWCdidReceiveMessage = "NotificationWCdidReceiveMessage"
let NotificationWCdidReceiveApplicationContext = "NotificationWCdidReceiveApplicationContext"
let NotificationWCdidReceiveUserInfo = "NotificationWCdidReceiveUserInfo"
class WatchConnectivityManager: NSObject {
class var sharedInstance: WatchConnectivityManager {
struct Singleton {
static let instance = WatchConnectivityManager()
}
return Singleton.instance
}
var session: WCSession? {
didSet {
if let session = session {
session.delegate = self
session.activateSession()
}
}
}
func activateSession() {
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
}
}
}
extension WatchConnectivityManager : WCSessionDelegate {
func sessionWatchStateDidChange(session: WCSession) {
print("sessionWatchStateDidChange session.paired=\(session.paired) ...")
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCsessionWatchStateDidChange,
object: session, userInfo: nil)
}
}
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]){
print("didReceiveUserInfo ...")
let trackItem = TrackDataItem.fromDictionary(userInfo)
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveUserInfo,
object: trackItem, userInfo: userInfo)
}
}
// func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
// print("didReceiveMessage ...")
// let trackItem = TrackDataItem.fromDictionary(message)
// dispatch_async(dispatch_get_main_queue()) {
// NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveMessage,
// object: trackItem, userInfo: message)
// }
// }
//
// func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
// print("didReceiveApplicationContext ...")
// let trackItem = TrackDataItem.fromDictionary(applicationContext)
// dispatch_async(dispatch_get_main_queue()) {
// NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveApplicationContext,
// object: trackItem, userInfo: applicationContext)
// }
// }
}
| mit |
YOCKOW/SwiftCGIResponder | Tests/CGIResponderTests/CGIResponderTests.swift | 1 | 6061 | /* *************************************************************************************************
CGIResponderTests.swift
© 2017-2021 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
************************************************************************************************ */
import XCTest
@testable import CGIResponder
import Foundation
import TemporaryFile
let CRLF = "\u{0D}\u{0A}"
private extension CGIResponder {
mutating func _resetEnvironment(_ newEnvironment: Environment = .virtual(variables: .virtual([:]))) {
self._environment = newEnvironment
}
}
final class CGIResponderTests: XCTestCase {
func test_contentType() {
var responder = CGIResponder()
XCTAssertEqual(responder.contentType, ContentType(type:.application, subtype:"octet-stream"))
let text_utf8_contentType = ContentType(type:.text, subtype:"plain", parameters:["charset":"UTF-8"])!
responder.contentType = text_utf8_contentType
XCTAssertEqual(responder.contentType.type, .text)
XCTAssertEqual(responder.contentType.subtype, "plain")
XCTAssertEqual(responder.stringEncoding, .utf8)
}
func test_expectedStatus_ETag() {
let eTag: HTTPETag = .strong("ETAG")
var responder = CGIResponder()
let HTTP_IF_MATCH = "HTTP_IF_MATCH"
let HTTP_IF_NONE_MATCH = "HTTP_IF_NONE_MATCH"
responder.header.insert(HTTPHeaderField.eTag(eTag))
XCTAssertNil(responder.expectedStatus)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_MATCH] = #""ETAG""#
XCTAssertNil(responder.expectedStatus)
responder._environment.variables[HTTP_IF_MATCH] = #""OTHER""#
XCTAssertEqual(responder.expectedStatus, .preconditionFailed)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_NONE_MATCH] = #"W/"ETAG""#
XCTAssertEqual(responder.expectedStatus, .notModified)
responder._environment.variables[HTTP_IF_NONE_MATCH] = #"W/"OTHER""#
XCTAssertNil(responder.expectedStatus)
}
func test_expectedStatus_Date() {
let date_base = DateFormatter.rfc1123.date(from:"Mon, 03 Oct 1983 16:21:09 GMT")!
let date_old = date_base - 1000
let date_new = date_base + 1000
let HTTP_IF_UNMODIFIED_SINCE = "HTTP_IF_UNMODIFIED_SINCE"
let HTTP_IF_MODIFIED_SINCE = "HTTP_IF_MODIFIED_SINCE"
func date_string(_ date:Date) -> String {
return DateFormatter.rfc1123.string(from:date)
}
var responder = CGIResponder()
responder.header.insert(HTTPHeaderField.lastModified(date_base))
XCTAssertNil(responder.expectedStatus)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_old)
XCTAssertEqual(responder.expectedStatus, .preconditionFailed)
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_base)
XCTAssertEqual(responder.expectedStatus, nil)
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_new)
XCTAssertEqual(responder.expectedStatus, nil)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_old)
XCTAssertEqual(responder.expectedStatus, nil)
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_base)
XCTAssertEqual(responder.expectedStatus, .notModified)
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_new)
XCTAssertEqual(responder.expectedStatus, .notModified)
}
func test_response() throws {
var responder = CGIResponder()
func check(_ expectedOutput: String?,
expectedError: CGIResponderError? = nil,
file: StaticString = #file, line: UInt = #line) throws {
try TemporaryFile {
var output = $0
let respond: () throws -> Void = { try responder.respond(to: &output, ignoringError: { _ in false }) }
if let expectedError = expectedError {
do {
try respond()
XCTFail("No throw.", file: file, line: line)
} catch {
let error = try XCTUnwrap(error as? CGIResponderError)
XCTAssertEqual(error, expectedError, "Unexpected Error.", file: file, line: line)
XCTAssertNil(expectedOutput)
}
} else {
XCTAssertNoThrow(try respond(), file: file, line: line)
try output.seek(toOffset:0)
let data = output.availableData
XCTAssertEqual(expectedOutput, String(data:data, encoding:.utf8), file:file, line:line)
}
}
}
responder.status = .ok
responder.contentType = ContentType(type:.text, subtype:"plain")!
responder.stringEncoding = .utf8
responder.content = .init(string:"CGI")
try check(
"Status: 200 OK\(CRLF)" +
"Content-Type: text/plain; charset=utf-8\(CRLF)" +
"\(CRLF)" +
"CGI"
)
responder.stringEncoding = .ascii
try check(
nil,
expectedError: .stringEncodingInconsistency(actualEncoding: .utf8, specifiedEncoding: .ascii)
)
}
func test_fallback() throws {
struct _Fallback: CGIFallback {
var status: HTTPStatusCode
var fallbackContent: CGIContent
init(_ error: CGIError) {
self.status = error.status
self.fallbackContent = .string(error.localizedDescription, encoding: .utf8)
}
}
struct _Error: CGIError {
var status: HTTPStatusCode = .notFound
var localizedDescription: String = "Not Found."
}
let responder = CGIResponder(content: .lazy({ throw _Error() }))
var output = InMemoryFile()
responder.respond(to: &output, fallback: { _Fallback($0) })
try output.seek(toOffset: 0)
let outputString = try output.readToEnd().flatMap({ String(data: $0, encoding: .utf8) })
XCTAssertEqual(
outputString,
"Status: 404 Not Found\(CRLF)" +
"Content-Type: text/plain; charset=utf-8\(CRLF)" +
"\(CRLF)" +
"Not Found."
)
}
}
| mit |
mmoaay/MBNetwork | Bamboots/Classes/Core/Extension/UIAlertController+Messageable.swift | 1 | 815 | //
// UIAlertController+Messageable.swift
// Pods
//
// Created by zhengperry on 2017/2/5.
//
//
import Foundation
extension UIAlertController: Informable {
public func show() {
UIApplication.shared.keyWindow?
.rootViewController?.present(
self,
animated: true,
completion: nil
)
}
}
extension UIAlertController: Warnable{
public func show(error: Errorable?) {
if let err = error {
if "" != err.message {
message = err.message
UIApplication.shared.keyWindow?
.rootViewController?.present(
self,
animated: true,
completion: nil
)
}
}
}
}
| mit |
yskamoona/a-ds | Playground/w2/DSPlayground/DSPlaygroundTests/DSPlaygroundTests.swift | 1 | 984 | //
// DSPlaygroundTests.swift
// DSPlaygroundTests
//
// Created by Yousra Kamoona on 6/17/17.
// Copyright © 2017 ysk. All rights reserved.
//
import XCTest
@testable import DSPlayground
class DSPlaygroundTests: 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.
}
}
}
| mit |
pinterest/tulsi | src/TulsiGenerator/TulsiApplicationSupport.swift | 2 | 3997 | // Copyright 2018 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
class ApplicationSupport {
private let fileManager: FileManager
let tulsiFolder: URL
init?(fileManager: FileManager = .default) {
// Fail if we are running in a test so that we don't install files to ~/Library/Application Support.
if ProcessInfo.processInfo.environment["TEST_SRCDIR"] != nil {
return nil
}
/// Fetching the appName this way will result in failure for our tests, which is intentional as
/// we don't want to install files to ~/Library/Application Support when testing.
guard let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { return nil }
guard let folder = fileManager.urls(for: .applicationSupportDirectory,
in: .userDomainMask).first else {
return nil
}
self.fileManager = fileManager
self.tulsiFolder = folder.appendingPathComponent(appName, isDirectory: true)
}
/// Copies Tulsi aspect files over to ~/Library/Application\ Support/Tulsi/<version>/Bazel and
/// returns the folder.
func copyTulsiAspectFiles(tulsiVersion: String) throws -> String {
let bundle = Bundle(for: type(of: self))
let aspectWorkspaceFile = bundle.url(forResource: "WORKSPACE", withExtension: nil)!
let aspectBuildFile = bundle.url(forResource: "BUILD", withExtension: nil)!
let tulsiFiles = bundle.urls(forResourcesWithExtension: nil, subdirectory: "tulsi")!
let bazelSubpath = (tulsiVersion as NSString).appendingPathComponent("Bazel")
let bazelPath = try installFiles([aspectWorkspaceFile, aspectBuildFile], toSubpath: bazelSubpath)
let tulsiAspectsSubpath = (bazelSubpath as NSString).appendingPathComponent("tulsi")
try installFiles(tulsiFiles, toSubpath: tulsiAspectsSubpath)
return bazelPath.path
}
@discardableResult
private func installFiles(_ files: [URL],
toSubpath subpath: String) throws -> URL {
let folder = tulsiFolder.appendingPathComponent(subpath, isDirectory: true)
try createDirectory(atURL: folder)
for sourceURL in files {
let filename = sourceURL.lastPathComponent
guard let targetURL = URL(string: filename, relativeTo: folder) else {
throw TulsiXcodeProjectGenerator.GeneratorError.serializationFailed(
"Unable to resolve URL for \(filename) in \(folder.path).")
}
do {
try copyFileIfNeeded(fromURL: sourceURL, toURL: targetURL)
}
}
return folder
}
private func copyFileIfNeeded(fromURL: URL, toURL: URL) throws {
do {
// Only over-write if needed.
if fileManager.fileExists(atPath: toURL.path) {
guard !fileManager.contentsEqual(atPath: fromURL.path, andPath: toURL.path) else {
return;
}
print("Overwriting \(toURL.path) as its contents changed.")
try fileManager.removeItem(at: toURL)
}
try fileManager.copyItem(at: fromURL, to: toURL)
}
}
private func createDirectory(atURL url: URL) throws {
var isDirectory: ObjCBool = false
let fileExists = fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
guard !fileExists || !isDirectory.boolValue else { return }
try fileManager.createDirectory(at: url,
withIntermediateDirectories: true,
attributes: nil)
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/00461-swift-clangmoduleunit-getadaptermodule.swift | 11 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class B<H where g:A{let h=c | mit |
allenu/SimpleLists | SimpleLists/Document.swift | 1 | 2039 | //
// Document.swift
// SimpleLists
//
// Created by Allen Ussher on 3/11/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import Cocoa
class Document: NSDocument {
fileprivate var names: [String] = []
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
self.addWindowController(windowController)
}
override func data(ofType typeName: String) throws -> Data {
let data = try JSONSerialization.data(withJSONObject: names, options: .prettyPrinted)
return data
}
override func read(from data: Data, ofType typeName: String) throws {
if let names = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0)) as? [String] {
self.names = names
} else {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
func touch() {
self.updateChangeCount(.changeDone)
}
}
//
// Public API
//
extension Document {
var numNames: Int {
return names.count
}
func name(atIndex index: Int) -> String? {
if index >= 0 && index < names.count {
return names[index]
} else {
return nil
}
}
func add(name: String) {
names.append(name)
touch()
}
func add(name: String, at index: Int) {
names.insert(name, at: index)
touch()
}
func remove(at index: Int) {
if index >= 0 && index < names.count {
names.remove(at: index)
touch()
}
}
}
| mit |
allen-garvey/font-check | Font Check/AppDelegate.swift | 1 | 589 | //
// AppDelegate.swift
// Font Check
//
// Created by Allen Xavier on 2/5/15.
// Copyright (c) 2015 Allen Garvey. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true;
}
}
| mit |
liuxianghong/GreenBaby | 工程/greenbaby/greenbaby/ViewController/ImageSeeViewController.swift | 1 | 2269 | //
// ImageSeeViewController.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/28.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
class ImageSeeViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
@IBOutlet weak var downLoadButton : UIButton!
var image : UIImage!
var imageUrl : String!
var hud : MBProgressHUD!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if image != nil{
imageView.image = image
}
else if imageUrl != nil{
imageView.sd_setImageWithURL(NSURL(string: imageUrl))
}
else{
imageView.image = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.dismissViewControllerAnimated(false) { () -> Void in
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
@IBAction func downClick(sender : UIButton){
if imageView.image == nil{
return;
}
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
UIImageWriteToSavedPhotosAlbum(imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
hud.mode = .Text
if error != nil {
hud.detailsLabelText = "保存失败,\(error!.localizedDescription)"
}
else{
hud.detailsLabelText = "保存成功"
}
hud.hide(true, afterDelay: 1.5)
}
/*
// 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.
}
*/
}
| lgpl-3.0 |
Boilertalk/VaporFacebookBot | Sources/VaporFacebookBot/Send/FacebookSendAttachmentGenericTemplate.swift | 1 | 6699 | //
// FacebookSendAttachmentGenericTemplate.swift
// VaporFacebookBot
//
// Created by Koray Koska on 26/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookSendAttachmentGenericTemplate: FacebookSendAttachmentTemplate {
public static var templateType: FacebookSendAttachmentTemplateType {
return .generic
}
public var sharable: Bool?
public var imageAspectRatio: FacebookSendAttachmentImageRatio?
public var elements: [FacebookSendAttachmentGenericElement]
public init(sharable: Bool? = nil, imageAspectRatio: FacebookSendAttachmentImageRatio? = nil, elements: [FacebookSendAttachmentGenericElement]) {
self.sharable = sharable
self.imageAspectRatio = imageAspectRatio
self.elements = elements
}
public convenience init(json: JSON) throws {
let sharable = json["sharable"]?.bool
let imageAspectRatioString = json["image_aspect_ratio"]?.string
let imageAspectRatio = imageAspectRatioString == nil ? nil : FacebookSendAttachmentImageRatio(rawValue: imageAspectRatioString!)
guard let elementsArray = json["elements"]?.array else {
throw Abort(.badRequest, metadata: "elements must be set for FacebookSendAttachmentGenericTemplate")
}
var elements = [FacebookSendAttachmentGenericElement]()
for e in elementsArray {
try elements.append(FacebookSendAttachmentGenericElement(json: e))
}
self.init(sharable: sharable, imageAspectRatio: imageAspectRatio, elements: elements)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("template_type", type(of: self).templateType.rawValue)
if let sharable = sharable {
try json.set("sharable", sharable)
}
if let imageAspectRatio = imageAspectRatio {
try json.set("image_aspect_ratio", imageAspectRatio.rawValue)
}
try json.set("elements", elements.jsonArray())
return json
}
}
public enum FacebookSendAttachmentImageRatio: String {
case horizontal = "horizontal"
case square = "square"
}
public final class FacebookSendAttachmentGenericElement: JSONConvertible {
public var title: String
public var subtitle: String?
public var imageUrl: String?
public var defaultAction: FacebookSendAttachmentGenericDefaultAction?
public var buttons: [FacebookSendButton]?
public init(
title: String,
subtitle: String? = nil,
imageUrl: String? = nil,
defaultAction: FacebookSendAttachmentGenericDefaultAction? = nil,
buttons: [FacebookSendButton]? = nil) {
self.title = title
self.subtitle = subtitle
self.imageUrl = imageUrl
self.defaultAction = defaultAction
self.buttons = buttons
}
public convenience init(json: JSON) throws {
let title: String = try json.get("title")
let subtitle = json["subtitle"]?.string
let imageUrl = json["image_url"]?.string
var defaultAction: FacebookSendAttachmentGenericDefaultAction? = nil
if let j = json["default_action"] {
defaultAction = try FacebookSendAttachmentGenericDefaultAction(json: j)
}
var buttons: [FacebookSendButton]? = nil
if let buttonsArray = json["buttons"]?.array {
buttons = [FacebookSendButton]()
for b in buttonsArray {
try buttons?.append(FacebookSendButtonHolder(json: b).button)
}
}
self.init(title: title, subtitle: subtitle, imageUrl: imageUrl, defaultAction: defaultAction, buttons: buttons)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("title", title)
if let subtitle = subtitle {
try json.set("subtitle", subtitle)
}
if let imageUrl = imageUrl {
try json.set("image_url", imageUrl)
}
if let defaultAction = defaultAction {
try json.set("default_action", defaultAction.makeJSON())
}
if let buttons = buttons {
var jArray = [JSON]()
for b in buttons {
jArray.append(try b.makeJSON())
}
try json.set("buttons", jArray)
}
return json
}
}
// TODO: The only difference between this class and FacebookSendURLButton is that this one does not support `title`. Maybe there is a better solution than duplicating it...
public final class FacebookSendAttachmentGenericDefaultAction: JSONConvertible {
public let type = "web_url"
public var url: String
public var webviewHeightRatio: FacebookSendWebviewHeightRatio?
public var messengerExtensions: Bool?
public var fallbackUrl: String?
public var webviewShareButton: String?
public init(
url: String,
webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil,
messengerExtensions: Bool? = nil,
fallbackUrl: String? = nil,
webviewShareButton: String? = nil) {
self.url = url
self.webviewHeightRatio = webviewHeightRatio
self.messengerExtensions = messengerExtensions
self.fallbackUrl = fallbackUrl
self.webviewShareButton = webviewShareButton
}
public convenience init(json: JSON) throws {
let url: String = try json.get("url")
var webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil
if let w = json["webview_height_ratio"]?.string {
webviewHeightRatio = FacebookSendWebviewHeightRatio(rawValue: w)
}
let messengerExtensions = json["messenger_extensions"]?.bool
let fallbackUrl = json["fallback_url"]?.string
let webviewShareButton = json["webview_share_button"]?.string
self.init(url: url, webviewHeightRatio: webviewHeightRatio, messengerExtensions: messengerExtensions, fallbackUrl: fallbackUrl, webviewShareButton: webviewShareButton)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("type", type)
try json.set("url", url)
if let webviewHeightRatio = webviewHeightRatio {
try json.set("webview_height_ratio", webviewHeightRatio.rawValue)
}
if let messengerExtensions = messengerExtensions {
try json.set("messenger_extensions", messengerExtensions)
}
if let fallbackUrl = fallbackUrl {
try json.set("fallback_url", fallbackUrl)
}
if let webviewShareButton = webviewShareButton {
try json.set("webview_share_button", webviewShareButton)
}
return json
}
}
| mit |
furuya02/CountDownView | CountDownSample/AppDelegate.swift | 1 | 2192 | //
// AppDelegate.swift
// CountDownSample
//
// Created by hirauchi.shinichi on 2016/12/07.
// Copyright © 2016年 SAPPOROWORKS. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
kickstarter/ios-oss | KsApi/models/MessageSubject.swift | 2 | 885 | public enum MessageSubject {
case backing(Backing)
case messageThread(MessageThread)
case project(Project)
public var backing: Backing? {
if case let .backing(backing) = self {
return backing
}
return nil
}
public var messageThread: MessageThread? {
if case let .messageThread(messageThread) = self {
return messageThread
}
return nil
}
public var project: Project? {
if case let .project(project) = self {
return project
}
return nil
}
}
extension MessageSubject: Equatable {}
public func == (lhs: MessageSubject, rhs: MessageSubject) -> Bool {
switch (lhs, rhs) {
case let (.backing(lhs), .backing(rhs)):
return lhs == rhs
case let (.messageThread(lhs), .messageThread(rhs)):
return lhs == rhs
case let (.project(lhs), .project(rhs)):
return lhs == rhs
default:
return false
}
}
| apache-2.0 |
shoheiyokoyama/SYBlinkAnimationKit | Example/SYBlinkAnimationKit/TextFieldViewController.swift | 2 | 1964 | //
// TextFieldViewController.swift
// SYBlinkAnimationKit
//
// Created by Shoehi Yokoyama on 2015/12/13.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
import SYBlinkAnimationKit
class TextFieldViewController: UIViewController {
@IBOutlet private weak var borderTextField: SYTextField!
@IBOutlet private weak var border2TextField: SYTextField!
@IBOutlet private weak var backgrondTextField: SYTextField!
@IBOutlet private weak var rippleTextField: SYTextField!
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
private func configure() {
self.view.backgroundColor = .white
self.navigationItem.title = "SYTextField"
borderTextField.placeholder = "Border Animation"
borderTextField.delegate = self
borderTextField.startAnimating()
view.addSubview(borderTextField)
border2TextField.placeholder = "BorderWithShadow Animation"
border2TextField.delegate = self
border2TextField.animationType = .borderWithShadow
border2TextField.backgroundColor = .clear
border2TextField.startAnimating()
view.addSubview(border2TextField)
backgrondTextField.placeholder = "Background Animation"
backgrondTextField.delegate = self
backgrondTextField.animationType = .background
backgrondTextField.startAnimating()
view.addSubview(backgrondTextField)
rippleTextField.placeholder = "Ripple Animation"
rippleTextField.delegate = self
rippleTextField.animationType = .ripple
rippleTextField.startAnimating()
view.addSubview(rippleTextField)
}
}
//MARK: - UITextFieldDelegate
extension TextFieldViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit |
castial/Quick-Start-iOS | Quick-Start-iOS/Controllers/Location/Protocol/EmptyPresenter.swift | 1 | 2128 | //
// EmptyPresenter.swift
// Quick-Start-iOS
//
// Created by work on 2016/12/10.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
struct EmptyOptions {
let message: String
let messageFont: UIFont
let messageColor: UIColor
let backgroundColor: UIColor
init(message: String = "暂无数据", messageFont: UIFont = UIFont.systemFont(ofSize: 16), messageColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.white) {
self.message = message
self.messageFont = messageFont
self.messageColor = messageColor
self.backgroundColor = backgroundColor
}
}
protocol EmptyPresenter {
func presentEmpty(emptyOptions: EmptyOptions)
}
extension EmptyPresenter where Self: UIView {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.addSubview(emptyView)
}
}
extension EmptyPresenter where Self: UIViewController {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.view.addSubview(emptyView)
}
}
extension EmptyPresenter {
// default empty view
fileprivate func defaultEmptyView(emptyOptions: EmptyOptions) -> UIView {
let emptyView = UIView (frame: CGRect (x: 0,
y: 0,
width: UIScreen.main.bounds.size.width,
height: UIScreen.main.bounds.size.height))
emptyView.backgroundColor = emptyOptions.backgroundColor
// add a message label
let messageLabel = UILabel()
messageLabel.text = emptyOptions.message
messageLabel.font = emptyOptions.messageFont
messageLabel.textColor = emptyOptions.messageColor
messageLabel.textAlignment = .center
messageLabel.sizeToFit()
messageLabel.center = emptyView.center
emptyView.addSubview(messageLabel)
return emptyView
}
}
| mit |
son11592/STNavigationViewController | Example/STNavigationViewController/HideNavigationViewController.swift | 1 | 2009 | //
// HideNavigationViewController.swift
// STNavigationViewController
//
// Created by Sơn Thái on 7/17/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class HideNavigationViewController: ViewController {
internal let navigation = NavigationBar()
internal let titleLb = UILabel()
internal let segment = UISegmentedControl(items: ["0.23s", "3s", "5s"])
override func commonInit() {
super.commonInit()
self.contentView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
}
override func loadView() {
super.loadView()
let mainBounds = UIScreen.main.bounds
self.navigation.setTitle("Hide Navigation View Controller")
self.navigationBar = self.navigation
self.titleLb.frame = CGRect(x: 15, y: 90, width: mainBounds.width - 30, height: 25)
self.titleLb.textColor = UIColor.black
self.titleLb.textAlignment = .center
self.titleLb.text = "Select duration for pop animation"
self.segment.frame = CGRect(x: 40, y: self.titleLb.frame.maxY + 20, width: mainBounds.width - 80, height: 40)
self.segment.selectedSegmentIndex = 0
self.contentView.addSubview(self.titleLb)
self.contentView.addSubview(self.segment)
self.contentView.addSubview(self.navigation)
}
override func getPopAnimatedTransitioning(from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning {
let animator = HideNavigationBarPopAnimator()
animator.duration = self.getDuration(from: self.segment)
return animator
}
override func getPopInteractionAnimatedTransitioning(from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning {
return HideNavigationBarPopAnimator()
}
private func getDuration(from segment: UISegmentedControl) -> TimeInterval {
switch segment.selectedSegmentIndex {
case 1:
return 3
case 2:
return 5
default:
return 0.23
}
}
}
| mit |
d4rkl0rd3r3b05/Data_Structure_And_Algorithm | LeetCode_AddTwoLinkedList.swift | 1 | 2828 | import Foundation
public class ListNode<T> : NSObject{
var nodeValue : T
var next : ListNode?
init(value : T) {
self.nodeValue = value
}
override public var description: String {
get{
return "\(self.nodeValue)->" + (self.next != nil ? self.next!.description : "NULL")
}
}
}
public class LinkedList<T> {
public var sourceElement : ListNode<T>?
public init(array : [T]) {
var previosNode : ListNode<T>?
for currentElement in array {
if self.sourceElement == nil {
self.sourceElement = ListNode(value: currentElement)
previosNode = self.sourceElement
}
else{
previosNode?.next = ListNode(value: currentElement)
previosNode = previosNode?.next
}
}
}
public static func addTwoList(firstList : ListNode<Int>?, secondList : ListNode<Int>?) -> ListNode<Int>? {
var solutionList : ListNode<Int>?
guard firstList != nil || secondList != nil else{
return nil
}
if firstList != nil {
if secondList != nil {
let sum = (firstList!.nodeValue + secondList!.nodeValue) % 10
let carryBalance = (firstList!.nodeValue + secondList!.nodeValue) / 10
var nextNode = secondList!.next
if carryBalance > 0 {
if nextNode == nil {
nextNode = ListNode(value: carryBalance)
}else{
nextNode!.nodeValue += carryBalance
}
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
else {
let sum = firstList!.nodeValue % 10
let carryBalance = firstList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
}else {
let sum = secondList!.nodeValue % 10
let carryBalance = secondList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: nextNode, secondList: secondList!.next)
}
return solutionList
}
}
| mit |
hsuanan/Mr-Ride-iOS | Mr-Ride/View/HistoryCustomHeaderCell.swift | 1 | 1042 | //
// HistoryCustomHeaderCell.swift
// Mr-Ride
//
// Created by Hsin An Hsu on 6/14/16.
// Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved.
//
import UIKit
class HistoryCustomHeaderCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var headerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
headerView.backgroundColor = UIColor.whiteColor()
headerView.layer.cornerRadius = 2
dateLabel.textColor = UIColor.mrDarkSlateBlueColor()
letterSpacing(dateLabel.text!, letterSpacing: -0.3, label: dateLabel)
}
func letterSpacing(text: String, letterSpacing: Double, label: UILabel){
let attributedText = NSMutableAttributedString (string: text)
attributedText.addAttribute(NSKernAttributeName, value: letterSpacing, range: NSMakeRange(0, attributedText.length))
label.attributedText = attributedText
}
}
| mit |
solszl/Shrimp500px | Shrimp500px/Views/Cells/BaseCell.swift | 1 | 231 | //
// BaseTableViewCell.swift
// Shrimp500px
//
// Created by 振亮 孙 on 16/2/27.
// Copyright © 2016年 papa.studio. All rights reserved.
//
import UIKit
protocol CellConfigData {
func configData(data: AnyObject?)
}
| mit |
eugenegolovanov/SocketChat | SocketChat/SocketIOManager.swift | 1 | 4154 | //
// SocketIOManager.swift
// SocketChat
//
// Created by eugene golovanov on 6/15/16.
// Copyright © 2016 AppCoda. All rights reserved.
//
import UIKit
class SocketIOManager: NSObject {
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Properties
static let sharedInstance = SocketIOManager()
// var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.0.4:3000")!)//HOME
var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.10.234:3000")!)//WORK
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Init
override init() {
super.init()
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Connection
func establishConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Operations
func connectToServerWithNickname(nickname: String, completionHandler: (userList: [[String: AnyObject]]!) -> Void) {
socket.emit("connectUser", nickname)
socket.on("userList") { ( dataArray, ack) -> Void in
completionHandler(userList: dataArray[0] as! [[String: AnyObject]])
}
listenForOtherMessages()
}
func exitChatWithNickname(nickname: String, completionHandler: () -> Void) {
socket.emit("exitUser", nickname)
completionHandler()
}
func sendMessage(message: String, withNickname nickname: String) {
socket.emit("chatMessage", nickname, message)
}
func getChatMessage(completionHandler: (messageInfo: [String: AnyObject]) -> Void) {
socket.on("newChatMessage") { (dataArray, socketAck) -> Void in
var messageDictionary = [String: AnyObject]()
messageDictionary["nickname"] = dataArray[0] as! String
messageDictionary["message"] = dataArray[1] as! String
messageDictionary["date"] = dataArray[2] as! String
completionHandler(messageInfo: messageDictionary)
}
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Listen users connection disconnection and typing
private func listenForOtherMessages() {
//send the respective information using the 'object' property of the notification
socket.on("userConnectUpdate") { (dataArray, socketAck) -> Void in
//the server returns a dictionary that contains all the new user information
NSNotificationCenter.defaultCenter().postNotificationName("userWasConnectedNotification", object: dataArray[0] as! [String: AnyObject])
}
socket.on("userExitUpdate") { (dataArray, socketAck) -> Void in
//the server returns just the nickname of the user that left the chat
NSNotificationCenter.defaultCenter().postNotificationName("userWasDisconnectedNotification", object: dataArray[0] as! String)
}
socket.on("userTypingUpdate") { (dataArray, socketAck) -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("userTypingNotification", object: dataArray[0] as? [String: AnyObject])
}
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Typing
func sendStartTypingMessage(nickname: String) {
socket.emit("startType", nickname)
}
func sendStopTypingMessage(nickname: String) {
socket.emit("stopType", nickname)
}
}
| unlicense |
Hansoncoder/Metal | MetalDemo/MetalCube/Cube.swift | 1 | 1394 | //
// Cube.swift
// MetalDemo
//
// Created by Hanson on 16/6/3.
// Copyright © 2016年 Hanson. All rights reserved.
//
import Foundation
import Metal
class Cube: Node {
init(device: MTLDevice) {
// 顶点数据
let A = Vertex(x: -1.0, y: 1.0, z: 1.0, w: 1.0, r: 1.0, g: 0.0, b: 0.0, a: 1.0)
let B = Vertex(x: -1.0, y: -1.0, z: 1.0, w: 1.0, r: 0.5, g: 1.0, b: 0.5, a: 1.0)
let C = Vertex(x: 1.0, y: -1.0, z: 1.0, w: 1.0, r: 0.0, g: 0.0, b: 1.0, a: 1.0)
let D = Vertex(x: 1.0, y: 1.0, z: 1.0, w: 1.0, r: 0.0, g: 0.0, b: 0.0, a: 1.0)
let Q = Vertex(x: -1.0, y: 1.0, z: -1.0, w: 1.0, r: 0.0, g: 1.0, b: 1.0, a: 1.0)
let R = Vertex(x: 1.0, y: 1.0, z: -1.0, w: 1.0, r: 1.0, g: 1.0, b: 0.0, a: 1.0)
let S = Vertex(x: -1.0, y: -1.0, z: -1.0, w: 1.0, r: 1.0, g: 0.0, b: 1.0, a: 1.0)
let T = Vertex(x: 1.0, y: -1.0, z: -1.0, w: 1.0, r: 0.0, g: 0.0, b: 0.0, a: 1.0)
let vertexArr = [A, B, C, A, C, D, // 前面
R, T, S, Q, R, S, // 后面
Q, S, B, Q, B, A, // 左面
D, C, T, D, T, R, // 右面
Q, A, D, Q, D, R, // 上面
B, S, T, B, T, C] // 下面
// 创建节点
super.init(name: "Cube", vertices: vertexArr, device: device)
}
} | apache-2.0 |
dvidlui/iOS8-day-by-day | 25-notification-actions/NotifyTimely/NotifyTimely/TimerNotifications.swift | 1 | 4728 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
let restartTimerActionString = "RestartTimer"
let editTimerActionString = "EditTimer"
let snoozeTimerActionString = "SnoozeTimer"
let timerFiredCategoryString = "TimerFiredCategory"
protocol TimerNotificationManagerDelegate {
func timerStatusChanged()
func presentEditOptions()
}
class TimerNotificationManager: Printable {
let snoozeDuration: Float = 5.0
var delegate: TimerNotificationManagerDelegate?
var timerRunning: Bool {
didSet {
delegate?.timerStatusChanged()
}
}
var timerDuration: Float {
didSet {
delegate?.timerStatusChanged()
}
}
var description: String {
if timerRunning {
return "\(timerDuration)s timer, running"
} else {
return "\(timerDuration)s timer, stopped"
}
}
init() {
timerRunning = false
timerDuration = 30.0
registerForNotifications()
checkForPreExistingTimer()
}
func startTimer() {
if !timerRunning {
// Create the notification...
scheduleTimerWithOffset(timerDuration)
}
}
func stopTimer() {
if timerRunning {
// Kill all local notifications
UIApplication.sharedApplication().cancelAllLocalNotifications()
timerRunning = false
}
}
func restartTimer() {
stopTimer()
startTimer()
}
func timerFired() {
timerRunning = false
}
func handleActionWithIdentifier(identifier: String?) {
timerRunning = false
if let identifier = identifier {
switch identifier {
case restartTimerActionString:
restartTimer()
case snoozeTimerActionString:
scheduleTimerWithOffset(snoozeDuration)
case editTimerActionString:
delegate?.presentEditOptions()
default:
println("Unrecognised Identifier")
}
}
}
// MARK: - Utility methods
private func checkForPreExistingTimer() {
if UIApplication.sharedApplication().scheduledLocalNotifications.count > 0 {
timerRunning = true
}
}
private func scheduleTimerWithOffset(fireOffset: Float) {
let timer = createTimer(fireOffset)
UIApplication.sharedApplication().scheduleLocalNotification(timer)
timerRunning = true
}
private func createTimer(fireOffset: Float) -> UILocalNotification {
let notification = UILocalNotification()
notification.category = timerFiredCategoryString
notification.fireDate = NSDate(timeIntervalSinceNow: NSTimeInterval(fireOffset))
notification.alertBody = "Your time is up!"
return notification
}
private func registerForNotifications() {
let requestedTypes = UIUserNotificationType.Alert | .Sound
let categories = NSSet(object: timerFiredNotificationCategory())
let settingsRequest = UIUserNotificationSettings(forTypes: requestedTypes, categories: categories)
UIApplication.sharedApplication().registerUserNotificationSettings(settingsRequest)
}
private func timerFiredNotificationCategory() -> UIUserNotificationCategory {
let restartAction = UIMutableUserNotificationAction()
restartAction.identifier = restartTimerActionString
restartAction.destructive = false
restartAction.title = "Restart"
restartAction.activationMode = .Background
restartAction.authenticationRequired = false
let editAction = UIMutableUserNotificationAction()
editAction.identifier = editTimerActionString
editAction.destructive = true
editAction.title = "Edit"
editAction.activationMode = .Foreground
editAction.authenticationRequired = true
let snoozeAction = UIMutableUserNotificationAction()
snoozeAction.identifier = snoozeTimerActionString
snoozeAction.destructive = false
snoozeAction.title = "Snooze"
snoozeAction.activationMode = .Background
snoozeAction.authenticationRequired = false
let category = UIMutableUserNotificationCategory()
category.identifier = timerFiredCategoryString
category.setActions([restartAction, snoozeAction], forContext: .Minimal)
category.setActions([restartAction, snoozeAction, editAction], forContext: .Default)
return category
}
}
| apache-2.0 |
steve-holmes/music-app-2 | MusicApp/Modules/Main/MainViewController.swift | 1 | 2826 | //
// MainViewController.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
import NSObject_Rx
class MainViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var tabbar: MainTabBarView!
@IBOutlet weak var borderView: MainBorderView!
@IBOutlet weak var imageView: MainImageView!
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
bindStore()
bindAction()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
configure()
}
// MARK: Configuration
func configure() {
let bottomDistance: CGFloat = 10
let center = CGPoint(
x: view.frame.size.width / 2,
y: view.frame.size.height - borderView.frame.size.height / 2 + bottomDistance
)
tabbar.configure(store: store, action: action)
borderView.configure(store: store, action: action, center: center)
imageView.configure(store: store, action: action, center: center)
}
// MARK: Status Bar
fileprivate var statusHidden = false
override var prefersStatusBarHidden: Bool {
return statusHidden
}
func setStatusBarHidden(_ hidden: Bool) {
statusHidden = hidden
setNeedsStatusBarAppearanceUpdate()
}
// MARK: Store and Action
var store: MainStore!
var action: MainAction!
private func bindStore() {
store.position.asObservable()
.distinctUntilChanged()
.subscribe(onNext: { [weak self] state in
self?.tabbar.setState(state)
})
.addDisposableTo(rx_disposeBag)
store.image.asObservable()
.subscribe(onNext: { [weak self] image in
self?.imageView.backgroundImage = image
})
.addDisposableTo(rx_disposeBag)
store.rotating.asObservable()
.skip(1)
.distinctUntilChanged()
.subscribe(onNext: { [weak self] rotating in
if rotating {
self?.imageView.startRotating()
} else {
self?.imageView.stopRotating()
}
})
.addDisposableTo(rx_disposeBag)
store.iconVisible.asObservable()
.distinctUntilChanged()
.subscribe(onNext: { [weak self] visible in
self?.imageView.visible = visible
})
.addDisposableTo(rx_disposeBag)
}
}
extension MainViewController {
func bindAction() {
}
}
| mit |
noppoMan/Prorsum | Sources/Prorsum/Go/Once.swift | 1 | 418 | //
// Once.swift
// Prorsum
//
// Created by Yuki Takei on 2016/11/23.
//
//
import Foundation
public class Once {
fileprivate let cond = Cond()
private var done = false
public func `do`(_ task: @escaping () -> Void){
cond.mutex.lock()
defer {
cond.mutex.unlock()
}
if !done {
done = true
task()
}
}
}
| mit |
minikin/Algorithmics | Pods/Charts/Charts/Classes/Data/Implementations/Standard/ChartDataSet.swift | 3 | 11391 | //
// ChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartDataSet: ChartBaseDataSet
{
public required init()
{
super.init()
_yVals = [ChartDataEntry]()
}
public override init(label: String?)
{
super.init(label: label)
_yVals = [ChartDataEntry]()
}
public init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(label: label)
_yVals = yVals == nil ? [ChartDataEntry]() : yVals
self.calcMinMax(start: _lastStart, end: _lastEnd)
}
public convenience init(yVals: [ChartDataEntry]?)
{
self.init(yVals: yVals, label: "DataSet")
}
// MARK: - Data functions and accessors
internal var _yVals: [ChartDataEntry]!
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
public var yVals: [ChartDataEntry] { return _yVals }
/// Use this method to tell the data set that the underlying data has changed
public override func notifyDataSetChanged()
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
public override func calcMinMax(start start: Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
let e = _yVals[i]
if (!e.value.isNaN)
{
if (e.value < _yMin)
{
_yMin = e.value
}
if (e.value > _yMax)
{
_yMax = e.value
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the minimum y-value this DataSet holds
public override var yMin: Double { return _yMin }
/// - returns: the maximum y-value this DataSet holds
public override var yMax: Double { return _yMax }
/// - returns: the number of y-values this DataSet represents
public override var entryCount: Int { return _yVals?.count ?? 0 }
/// - returns: the value of the Entry object at the given xIndex. Returns NaN if no value is at the given x-index.
public override func yValForXIndex(x: Int) -> Double
{
let e = self.entryForXIndex(x)
if (e !== nil && e!.xIndex == x) { return e!.value }
else { return Double.NaN }
}
/// - returns: the entry object found at the given index (not x-index!)
/// - throws: out of bounds
/// if `i` is out of bounds, it may throw an out-of-bounds exception
public override func entryForIndex(i: Int) -> ChartDataEntry?
{
return _yVals[i]
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public override func entryForXIndex(x: Int) -> ChartDataEntry?
{
let index = self.entryIndex(xIndex: x)
if (index > -1)
{
return _yVals[index]
}
return nil
}
public func entriesForXIndex(x: Int) -> [ChartDataEntry]
{
var entries = [ChartDataEntry]()
var low = 0
var high = _yVals.count - 1
while (low <= high)
{
var m = Int((high + low) / 2)
var entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
high = _yVals.count
for (; m < high; m++)
{
entry = _yVals[m]
if (entry.xIndex == x)
{
entries.append(entry)
}
else
{
break
}
}
}
if (x > _yVals[m].xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
}
return entries
}
/// - returns: the array-index of the specified entry
///
/// - parameter x: x-index of the entry to search for
public override func entryIndex(xIndex x: Int) -> Int
{
var low = 0
var high = _yVals.count - 1
var closest = -1
while (low <= high)
{
var m = (high + low) / 2
let entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
return m
}
if (x > entry.xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
closest = m
}
return closest
}
/// - returns: the array-index of the specified entry
///
/// - parameter e: the entry to search for
public override func entryIndex(entry e: ChartDataEntry) -> Int
{
for (var i = 0; i < _yVals.count; i++)
{
if _yVals[i] === e
{
return i
}
}
return -1
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to the end of the list.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
/// - returns: true
public override func addEntry(e: ChartDataEntry) -> Bool
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yVals.append(e)
return true
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to their appropriate index respective to it's x-index.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
/// - returns: true
public override func addEntryOrdered(e: ChartDataEntry) -> Bool
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
if _yVals.last?.xIndex > e.xIndex
{
var closestIndex = entryIndex(xIndex: e.xIndex)
if _yVals[closestIndex].xIndex < e.xIndex
{
closestIndex++
}
_yVals.insert(e, atIndex: closestIndex)
return true
}
_yVals.append(e)
return true
}
/// Removes an Entry from the DataSet dynamically.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter entry: the entry to remove
/// - returns: true if the entry was removed successfully, else if the entry does not exist
public override func removeEntry(entry: ChartDataEntry) -> Bool
{
var removed = false
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === entry)
{
_yVals.removeAtIndex(i)
removed = true
break
}
}
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
/// Removes the first Entry (at index 0) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public override func removeFirst() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeFirst()
let removed = entry != nil
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
/// Removes the last Entry (at index size-1) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public override func removeLast() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeLast()
let removed = entry != nil
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: true if contains the entry, false if not.
public override func contains(e: ChartDataEntry) -> Bool
{
for entry in _yVals
{
if (entry.isEqual(e))
{
return true
}
}
return false
}
/// Removes all values from this DataSet and recalculates min and max value.
public override func clear()
{
_yVals.removeAll(keepCapacity: true)
_lastStart = 0
_lastEnd = 0
notifyDataSetChanged()
}
// MARK: - Data functions and accessors
/// - returns: the number of entries this DataSet holds.
public var valueCount: Int { return _yVals.count }
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! ChartDataSet
copy._yVals = _yVals
copy._yMax = _yMax
copy._yMin = _yMin
copy._lastStart = _lastStart
copy._lastEnd = _lastEnd
return copy
}
}
| mit |
cbrentharris/swift | validation-test/compiler_crashers/28001-swift-parser-parsetypesimple.swift | 1 | 259 | // RUN: not --crash %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
struct X<T:T.a
class B{typealias F=
| apache-2.0 |
xedin/swift | test/TBD/enum.swift | 2 | 3531 | // Swift 3:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -O
// Swift 4:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -O
// With -enable-testing:
// Swift 3:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing -O
// Swift 4:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing -O
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/typecheck.tbd
// RUN: %target-swift-frontend -emit-ir -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/emit-ir.tbd
// RUN: diff -u %t/typecheck.tbd %t/emit-ir.tbd
public protocol P {}
public class C {
}
public enum SinglePayload: P {
case A
case B(C)
case D
}
public enum MultiPayload {
case A
case B(C)
case D(C)
public func method() {}
}
public enum AutomaticEquatableHashable {
case a, b
}
public enum Synthesized: Equatable, Hashable {
case a(AutomaticEquatableHashable), b
}
public enum ConditionalSynthesized<T> {
case a(T), b
}
#if swift(>=4)
extension ConditionalSynthesized: Equatable where T: Equatable {}
extension ConditionalSynthesized: Hashable where T: Hashable {}
#endif
public enum ZeroCases {}
public enum OneCase {
case a
}
public enum OneCasePayload {
case a(C)
}
| apache-2.0 |
zirinisp/SlackKit | SlackKit/Sources/Bot.swift | 1 | 1684 | //
// Bot.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// 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 struct Bot {
public let id: String?
internal(set) public var botToken: String?
internal(set) public var name: String?
internal(set) public var icons: [String: Any]?
internal init(bot: [String: Any]?) {
id = bot?["id"] as? String
name = bot?["name"] as? String
icons = bot?["icons"] as? [String: Any]
}
internal init(botUser: [String: Any]?) {
id = botUser?["bot_user_id"] as? String
botToken = botUser?["bot_access_token"] as? String
}
}
| mit |
lukesutton/yopuy | Sources/Request.swift | 1 | 1452 | import Foundation
/**
Encodes a request — path, URL, body etc — and is generated by the `Service`.
It's generic types are there for the `Path` instance it captures.
*/
public struct Request<R: Resource, P, M> {
/**
The `Path` for this request. Which encodes the `Resource`, the response —
single or many — and the HTTP method.
*/
public let path: Path<R, P, M>
/**
The fully-qualified URL for the request.
*/
public let URL: URL
/**
The values to be encoded into a query string.
*/
public let query: [String: String]?
/**
The request body encoded as a string.
*/
public let body: String?
fileprivate let _headers: [Header]?
/**
The request headers.
*/
public var headers: [Header]? {
return _headers
}
init(path: Path<R, P, M>, URL: URL, headers: [Header]?, query: [String: String]?, body: String?) {
self.path = path
self.URL = URL
self._headers = headers
self.query = query
self.body = body
}
}
/**
The `Request` type conforms to `AdapterRequest`, which allows it to be passed
to a `HTTPAdapter` type.
*/
extension Request: AdapterRequest {
/**
The request headers encoded as strings.
*/
public var headers: [String: String]? {
guard let headers = _headers else { return nil }
var result: [String: String] = [:]
for header in headers {
let (k, v) = header.pair
result[k] = v
}
return result
}
}
| mit |
groue/GRDB.swift | GRDB/QueryInterface/FTS3+QueryInterface.swift | 1 | 1962 | extension TableRequest where Self: FilteredRequest {
// MARK: Full Text Search
/// Filters rows that match an ``FTS3`` full-text pattern.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM book WHERE book MATCH 'sqlite OR database'
/// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database")
/// let request = Book.all().matching(pattern)
/// ```
///
/// If `pattern` is nil, the returned request fetches no row.
///
/// - parameter pattern: An ``FTS3Pattern``.
public func matching(_ pattern: FTS3Pattern?) -> Self {
guard let pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
}
}
extension TableRecord {
// MARK: Full Text Search
/// Returns a request filtered on records that match an ``FTS3``
/// full-text pattern.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM book WHERE book MATCH 'sqlite OR database'
/// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database")
/// let request = Book.matching(pattern)
/// ```
///
/// If `pattern` is nil, the returned request fetches no row.
///
/// - parameter pattern: An ``FTS3Pattern``.
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
all().matching(pattern)
}
}
extension ColumnExpression {
/// A matching SQL expression with the `MATCH` SQL operator.
///
/// // content MATCH '...'
/// Column("content").match(pattern)
///
/// If the search pattern is nil, SQLite will evaluate the expression
/// to false.
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
.binary(.match, sqlExpression, pattern?.sqlExpression ?? .null)
}
}
| mit |
SteveClement/Swifter | Swifter/SwifterAuth.swift | 1 | 8182 | //
// SwifterAuth.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public extension Swifter {
public typealias TokenSuccessHandler = (accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) -> Void
public func authorizeWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler?, failure: ((error: NSError) -> Void)? = nil, openQueryURL: ((url: NSURL) -> Void)?, closeQueryURL:(() -> Void)? = nil) {
self.postOAuthRequestTokenWithCallbackURL(callbackURL, success: {
token, response in
var requestToken = token!
NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{
notification in
NSNotificationCenter.defaultCenter().removeObserver(self)
closeQueryURL?()
let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL
let parameters = url.query!.parametersFromQueryString()
requestToken.verifier = parameters["oauth_verifier"]
self.postOAuthAccessTokenWithRequestToken(requestToken, success: {
accessToken, response in
self.client.credential = SwifterCredential(accessToken: accessToken!)
success?(accessToken: accessToken!, response: response)
}, failure: failure)
})
let authorizeURL = NSURL(string: "/oauth/authorize", relativeToURL: self.apiURL)
let queryURL = NSURL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")
if openQueryURL != nil {
openQueryURL?(url: queryURL!)
} else {
#if os(iOS)
UIApplication.sharedApplication().openURL(queryURL!)
#else
NSWorkspace.sharedWorkspace().openURL(queryURL!)
#endif
}
}, failure: failure)
}
public class func handleOpenURL(url: NSURL) {
let notification = NSNotification(name: CallbackNotification.notificationName, object: nil,
userInfo: [CallbackNotification.optionsURLKey: url])
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func authorizeAppOnlyWithSuccess(success: TokenSuccessHandler?, failure: FailureHandler?) {
self.postOAuth2BearerTokenWithSuccess({
json, response in
if let tokenType = json["token_type"].string {
if tokenType == "bearer" {
let accessToken = json["access_token"].string
let credentialToken = SwifterCredential.OAuthAccessToken(key: accessToken!, secret: "")
self.client.credential = SwifterCredential(accessToken: credentialToken)
success?(accessToken: credentialToken, response: response)
}
else {
let error = NSError(domain: "Swifter", code: SwifterError.appOnlyAuthenticationErrorCode, userInfo: [NSLocalizedDescriptionKey: "Cannot find bearer token in server response"]);
failure?(error: error)
}
}
else if let errors = json["errors"].object {
let error = NSError(domain: SwifterError.domain, code: errors["code"]!.integer!, userInfo: [NSLocalizedDescriptionKey: errors["message"]!.string!]);
failure?(error: error)
}
else {
let error = NSError(domain: SwifterError.domain, code: SwifterError.appOnlyAuthenticationErrorCode, userInfo: [NSLocalizedDescriptionKey: "Cannot find JSON dictionary in response"]);
failure?(error: error)
}
}, failure: failure)
}
public func postOAuth2BearerTokenWithSuccess(success: JSONSuccessHandler?, failure: FailureHandler?) {
let path = "/oauth2/token"
var parameters = Dictionary<String, Any>()
parameters["grant_type"] = "client_credentials"
self.jsonRequestWithPath(path, baseURL: self.apiURL, method: "POST", parameters: parameters, success: success, failure: failure)
}
public func postOAuth2InvalidateBearerTokenWithSuccess(success: TokenSuccessHandler?, failure: FailureHandler?) {
let path = "/oauth2/invalidate_token"
self.jsonRequestWithPath(path, baseURL: self.apiURL, method: "POST", parameters: [:], success: {
json, response in
if let accessToken = json["access_token"].string {
self.client.credential = nil
let credentialToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: "")
success?(accessToken: credentialToken, response: response)
}
else {
success?(accessToken: nil, response: response)
}
}, failure: failure)
}
public func postOAuthRequestTokenWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) {
let path = "/oauth/request_token"
var parameters = Dictionary<String, Any>()
parameters["oauth_callback"] = callbackURL.absoluteString
self.client.post(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
let accessToken = SwifterCredential.OAuthAccessToken(queryString: responseString as String!)
success(accessToken: accessToken, response: response)
}, failure: failure)
}
public func postOAuthAccessTokenWithRequestToken(requestToken: SwifterCredential.OAuthAccessToken, success: TokenSuccessHandler, failure: FailureHandler?) {
if let verifier = requestToken.verifier {
let path = "/oauth/access_token"
var parameters = Dictionary<String, Any>()
parameters["oauth_token"] = requestToken.key
parameters["oauth_verifier"] = verifier
self.client.post(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
let accessToken = SwifterCredential.OAuthAccessToken(queryString: responseString! as String)
success(accessToken: accessToken, response: response)
}, failure: failure)
}
else {
let userInfo = [NSLocalizedFailureReasonErrorKey: "Bad OAuth response received from server"]
let error = NSError(domain: SwifterError.domain, code: NSURLErrorBadServerResponse, userInfo: userInfo)
failure?(error: error)
}
}
}
| mit |
apple/swift-format | Tests/SwiftFormatPrettyPrintTests/PatternBindingTests.swift | 1 | 1466 | import SwiftFormatConfiguration
final class PatternBindingTests: PrettyPrintTestCase {
func testBindingIncludingTypeAnnotation() {
let input =
"""
let someObject: Foo = object
let someObject: (foo: Foo, bar: SomeVeryLongTypeNameThatDefinitelyBreaks, baz: Baz) = foo(a, b, c, d)
"""
let expected =
"""
let someObject: Foo = object
let someObject:
(
foo: Foo,
bar:
SomeVeryLongTypeNameThatDefinitelyBreaks,
baz: Baz
) = foo(a, b, c, d)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 40)
}
func testIgnoresDiscretionaryNewlineAfterColon() {
let input =
"""
let someObject:
Foo = object
let someObject:
Foo = longerObjectName
"""
let expected =
"""
let someObject: Foo = object
let someObject: Foo =
longerObjectName
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 28)
}
func testGroupingIncludesTrailingComma() {
let input =
"""
let foo = veryLongCondition
? firstOption
: secondOption,
bar = bar()
"""
let expected =
"""
let
foo =
veryLongCondition
? firstOption
: secondOption,
bar = bar()
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 18)
}
}
| apache-2.0 |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Storage/Database/SDSModel.swift | 1 | 4318 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
public protocol SDSModel: TSYapDatabaseObject {
var sdsTableName: String { get }
func asRecord() throws -> SDSRecord
var serializer: SDSSerializer { get }
func anyInsert(transaction: SDSAnyWriteTransaction)
func anyRemove(transaction: SDSAnyWriteTransaction)
static var table: SDSTableMetadata { get }
}
// MARK: -
public extension SDSModel {
func sdsSave(saveMode: SDSSaveMode, transaction: SDSAnyWriteTransaction) {
guard shouldBeSaved else {
Logger.warn("Skipping save of: \(type(of: self))")
return
}
switch saveMode {
case .insert:
anyWillInsert(with: transaction)
case .update:
anyWillUpdate(with: transaction)
}
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydb_save(with: ydbTransaction)
case .grdbWrite(let grdbTransaction):
do {
let record = try asRecord()
record.sdsSave(saveMode: saveMode, transaction: grdbTransaction)
} catch {
owsFail("Write failed: \(error)")
}
}
switch saveMode {
case .insert:
anyDidInsert(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasInserted(model: self, transaction: transaction)
}
case .update:
anyDidUpdate(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasUpdated(model: self, transaction: transaction)
}
}
}
func sdsRemove(transaction: SDSAnyWriteTransaction) {
guard shouldBeSaved else {
// Skipping remove.
return
}
anyWillRemove(with: transaction)
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydb_remove(with: ydbTransaction)
case .grdbWrite(let grdbTransaction):
// Don't use a record to delete the record;
// asRecord() is expensive.
let sql = """
DELETE
FROM \(sdsTableName)
WHERE uniqueId == ?
"""
grdbTransaction.executeWithCachedStatement(sql: sql, arguments: [uniqueId])
}
anyDidRemove(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasRemoved(model: self, transaction: transaction)
}
}
}
// MARK: -
public extension TableRecord {
static func ows_fetchCount(_ db: Database) -> UInt {
do {
let result = try fetchCount(db)
guard result >= 0 else {
owsFailDebug("Invalid result: \(result)")
return 0
}
guard result <= UInt.max else {
owsFailDebug("Invalid result: \(result)")
return UInt.max
}
return UInt(result)
} catch {
owsFailDebug("Read failed: \(error)")
return 0
}
}
}
// MARK: -
public extension SDSModel {
// If batchSize > 0, the enumeration is performed in autoreleased batches.
static func grdbEnumerateUniqueIds(transaction: GRDBReadTransaction,
sql: String,
batchSize: UInt,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
do {
let cursor = try String.fetchCursor(transaction.database,
sql: sql)
try Batching.loop(batchSize: batchSize,
loopBlock: { stop in
guard let uniqueId = try cursor.next() else {
stop.pointee = true
return
}
block(uniqueId, stop)
})
} catch let error as NSError {
owsFailDebug("Couldn't fetch uniqueIds: \(error)")
}
}
}
| gpl-3.0 |
HipHipArr/PocketCheck | Cheapify 2.0/View.swift | 1 | 1170 | //
// View.swift
// Cheapify 2.0
//
// Created by loaner on 7/8/15.
// Copyright (c) 2015 Your Friend. All rights reserved.
//
import UIKit
class View: UIImageView {
var bgImage: UIImage!
func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
setup()
}
func setup(){
self.bgImage = chooseImage(entryMgr.categoryname)
}
func chooseImage (cat: String) -> UIImage {
if(cat == "Food")
{
return UIImage(named: "food.jpg")!
}
else if(cat == "Personal")
{
return UIImage(named: "personal.jpg")!
}
else if(cat == "Travel")
{
return UIImage(named: "travel.jpg")!
}
else if(cat == "Transportation")
{
return UIImage(named: "transportation.jpg")!
}
else if(cat == "Business")
{
return UIImage(named: "business.jpg")!
}
else if(cat == "Entertainment")
{
return UIImage(named: "entertainment.jpg")!
}
return UIImage(named: "other.jpg")!
}
}
| mit |
charleshkang/Weatherr | C4QWeather/C4QWeather/WeatherParser.swift | 1 | 1254 | //
// WeatherParser
// C4QWeather
//
// Created by Charles Kang on 11/21/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import SwiftyJSON
class WeatherParser {
//MARK: Action Methods
/**
use flatMap instead of map here because data from a backend can always fail,
use flatMap so we only return successful weather objects
*/
func parseWeatherJSON(_ json: JSON) -> [Weather] {
let weatherArray = json["response"][0]["periods"].arrayValue
return weatherArray.flatMap { Weather(json: $0) }
}
}
extension Weather {
/**
create a failable initializer to make sure
we only get properties that are valid. also use
guard to take advantage of its early exit feature
*/
init?(json: JSON) {
guard let maxTempF = json["maxTempF"].int,
let minTempF = json["minTempF"].int,
let maxTempC = json["maxTempC"].int,
let minTempC = json["minTempC"].int,
let dateTimeISO = json["dateTimeISO"].string
else { return nil }
self.maxTempF = maxTempF
self.minTempF = minTempF
self.maxTempC = maxTempC
self.minTempC = minTempC
self.dateTime = dateTimeISO
}
}
| mit |
blinksh/blink | KB/Native/Views/General/DefaultRow.swift | 1 | 2037 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import SwiftUI
struct DefaultRow<Details: View>: View {
@Binding var title: String
@Binding var description: String?
var details: () -> Details
init(title: String, description: String? = nil, details: @escaping () -> Details) {
_title = .constant(title)
_description = .constant(description)
self.details = details
}
init(title: Binding<String>, description: Binding<String?> = .constant(nil), details: @escaping () -> Details) {
_title = title
_description = description
self.details = details
}
var body: some View {
Row(content: {
HStack {
Text(self.title).foregroundColor(.primary)
Spacer()
Text(self.description ?? "").foregroundColor(.secondary)
}
}, details: self.details)
}
}
| gpl-3.0 |
trm36/stanford-calculator | Calculator/ViewController.swift | 1 | 11544 | //
// ViewController.swift
// Calculator
//
// Created by Taylor Mott on 13 Jul 15.
// Copyright (c) 2015 Mott Applications. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let displayLabel = UILabel()
let displayBackground = UIView()
var userIsInTheMiddleOfTypingANumber = false
var displayValue: Double {
get {
return (displayLabel.text! as NSString).doubleValue
}
set {
self.displayLabel.text = "\(newValue)"
self.userIsInTheMiddleOfTypingANumber = false
}
}
let brain = CalculatorBrain()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Row 1
self.displayBackground.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(self.displayBackground)
self.displayLabel.text = "0"
self.displayLabel.font = UIFont.systemFontOfSize(32)
self.displayLabel.textAlignment = NSTextAlignment.Right
self.view.addSubview(self.displayLabel)
self.displayLabel.alignTop("20", leading: "5", toView: self.view)
self.displayLabel.alignTrailingEdgeWithView(self.view, predicate: "-5")
self.displayLabel.constrainHeight("50")
self.displayBackground.alignTop("0", leading: "0", bottom: "0", trailing: "0", toView: self.displayLabel)
//Row 2
let button7 = UIButton()
button7.setTitle("7", forState: .Normal)
button7.setTitleColor(UIColor.blackColor(), forState: .Normal)
button7.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button7)
let button8 = UIButton()
button8.setTitle("8", forState: .Normal)
button8.setTitleColor(UIColor.blackColor(), forState: .Normal)
button8.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button8)
let button9 = UIButton()
button9.setTitle("9", forState: .Normal)
button9.setTitleColor(UIColor.blackColor(), forState: .Normal)
button9.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button9)
let buttonDivide = UIButton()
buttonDivide.setTitle("÷", forState: .Normal)
buttonDivide.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonDivide.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonDivide)
button7.constrainTopSpaceToView(self.displayLabel, predicate: "5")
button7.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button8.alignTopEdgeWithView(button7, predicate: "0")
button8.constrainLeadingSpaceToView(button7, predicate: "0")
button9.alignTopEdgeWithView(button7, predicate: "0")
button9.constrainLeadingSpaceToView(button8, predicate: "0")
buttonDivide.alignTopEdgeWithView(button7, predicate: "0")
buttonDivide.constrainLeadingSpaceToView(button9, predicate: "0")
buttonDivide.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 3
let button4 = UIButton()
button4.setTitle("4", forState: .Normal)
button4.setTitleColor(UIColor.blackColor(), forState: .Normal)
button4.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button4)
let button5 = UIButton()
button5.setTitle("5", forState: .Normal)
button5.setTitleColor(UIColor.blackColor(), forState: .Normal)
button5.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button5)
let button6 = UIButton()
button6.setTitle("6", forState: .Normal)
button6.setTitleColor(UIColor.blackColor(), forState: .Normal)
button6.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button6)
let buttonMultiply = UIButton()
buttonMultiply.setTitle("×", forState: .Normal)
buttonMultiply.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonMultiply.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonMultiply)
button4.constrainTopSpaceToView(button7, predicate: "0")
button4.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button5.alignTopEdgeWithView(button4, predicate: "0")
button5.constrainLeadingSpaceToView(button4, predicate: "0")
button6.alignTopEdgeWithView(button4, predicate: "0")
button6.constrainLeadingSpaceToView(button5, predicate: "0")
buttonMultiply.alignTopEdgeWithView(button4, predicate: "0")
buttonMultiply.constrainLeadingSpaceToView(button6, predicate: "0")
buttonMultiply.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 4
let button1 = UIButton()
button1.backgroundColor = .redColor()
button1.setTitle("1", forState: .Normal)
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button1)
let button2 = UIButton()
button2.backgroundColor = .yellowColor()
button2.setTitle("2", forState: .Normal)
button2.setTitleColor(UIColor.blackColor(), forState: .Normal)
button2.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button2)
let button3 = UIButton()
button3.backgroundColor = .orangeColor()
button3.setTitle("3", forState: .Normal)
button3.setTitleColor(UIColor.blackColor(), forState: .Normal)
button3.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button3)
let buttonSubtract = UIButton()
buttonSubtract.setTitle("−", forState: .Normal)
buttonSubtract.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonSubtract.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonSubtract)
button1.constrainTopSpaceToView(button4, predicate: "0")
button1.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button2.alignTopEdgeWithView(button1, predicate: "0")
button2.constrainLeadingSpaceToView(button1, predicate: "0")
button3.alignTopEdgeWithView(button1, predicate: "0")
button3.constrainLeadingSpaceToView(button2, predicate: "0")
buttonSubtract.alignTopEdgeWithView(button1, predicate: "0")
buttonSubtract.constrainLeadingSpaceToView(button3, predicate: "0")
buttonSubtract.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 5
let buttonEnter = UIButton()
buttonEnter.backgroundColor = .purpleColor()
buttonEnter.setTitle("↩︎", forState: .Normal)
buttonEnter.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonEnter.addTarget(self, action: "enter", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonEnter)
let button0 = UIButton()
button0.backgroundColor = .blueColor()
button0.setTitle("0", forState: .Normal)
button0.setTitleColor(UIColor.blackColor(), forState: .Normal)
button0.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button0)
let buttonSqrt = UIButton()
buttonSqrt.setTitle("√", forState: .Normal)
buttonSqrt.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonSqrt.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonSqrt)
let buttonAdd = UIButton()
buttonAdd.setTitle("+", forState: .Normal)
buttonAdd.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonAdd.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonAdd)
buttonEnter.constrainTopSpaceToView(button1, predicate: "0")
buttonEnter.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
buttonEnter.alignBottomEdgeWithView(self.view, predicate: "-5")
button0.alignTopEdgeWithView(buttonEnter, predicate: "0")
button0.constrainLeadingSpaceToView(buttonEnter, predicate: "0")
buttonSqrt.alignTopEdgeWithView(buttonEnter, predicate: "0")
buttonSqrt.constrainLeadingSpaceToView(button0, predicate: "0")
buttonAdd.alignTopEdgeWithView(buttonEnter, predicate: "0")
buttonAdd.constrainLeadingSpaceToView(buttonSqrt, predicate: "0")
buttonAdd.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
UIView.equalHeightForViews([button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonEnter, buttonDivide, buttonMultiply, buttonSubtract, buttonAdd, buttonSqrt])
UIView.equalWidthForViews([button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonEnter, buttonDivide, buttonMultiply, buttonSubtract, buttonAdd, buttonSqrt])
}
func operate(sender: UIButton) {
let operation = sender.currentTitle!
if self.userIsInTheMiddleOfTypingANumber {
enter()
}
if let result = self.brain.performOperation(operation) {
displayValue = result
} else {
//get rid of display
println("error paul was talking about with display value not being an optional")
}
}
func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if !(digit == "0" && self.displayLabel.text! == "0") {
if userIsInTheMiddleOfTypingANumber && self.displayLabel.text! != "0" {
self.displayLabel.text = self.displayLabel.text! + digit
} else {
self.displayLabel.text = digit
}
}
self.userIsInTheMiddleOfTypingANumber = true
println("\(digit)")
println("\(self.userIsInTheMiddleOfTypingANumber)")
}
func enter () {
self.userIsInTheMiddleOfTypingANumber = false
if let result = self.brain.pushOperand(self.displayValue) {
self.displayValue = result
} else {
// get rid of display
println("error paul was talking about in lecture 3")
}
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.displayBackground.alpha = 0.5
}) { (_) -> Void in
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.displayBackground.alpha = 1.0
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
niekang/NKDownload | NKDownload/DownloadingViewController.swift | 1 | 3616 | //
// ViewController.swift
// NKDownload
//
// Created by 聂康 on 2017/5/15.
// Copyright © 2017年 聂康. All rights reserved.
//
import UIKit
class DownloadingViewController: UIViewController {
fileprivate let reuse = "DownloadCell"
fileprivate lazy var dataArr = [DownloadObject]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
NKDownloadManger.shared.delegate = self
dataArr = DownloadSqlite.manager.selectData()
}
}
extension DownloadingViewController{
/// 根据url获取对应的cell
///
/// - Parameter urlString: 下载url
/// - Returns: url对应的cell
func getCellWithURLString(urlString:String) -> DownloadCell?{
for (index,downloadObject) in dataArr.enumerated(){
if downloadObject.urlString == urlString {
let indexPath = IndexPath(row: index, section: 0)
let cell = tableView.cellForRow(at: indexPath) as? DownloadCell
return cell
}
}
return nil
}
}
extension DownloadingViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuse) as! DownloadCell
let downloadObject = dataArr[indexPath.row]
cell.disPlayCell(object: downloadObject)
return cell
}
}
extension DownloadingViewController:NKDownloadMangerDelegate{
func nk_downloadTaskStartDownload(nkDownloadTask: NKDownloadTask) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
cell.downloadObject.state = .downloading
cell.downloadBtn.setTitle("下载中", for: .normal)
}
}
/// 更新下载进度
///
/// - Parameter urlString: 下载网址
func nk_downloadTaskDidWriteData(nkDownloadTask: NKDownloadTask, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
cell.downloadObject.currentSize = totalBytesWritten
cell.downloadObject.totalSize = totalBytesExpectedToWrite
cell.downloadObject.state = .downloading
cell.disPlayCell(object: cell.downloadObject)
}
}
func nk_downloadTaskDidComleteWithError(nkDownloadTask: NKDownloadTask, error: NKDownloadError?) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
if let _ = error{
if error == NKDownloadError.cancelByUser{
cell.downloadObject.state = .suspend
}else if error == NKDownloadError.networkError{
cell.downloadObject.state = .fail
}
}else {
cell.downloadObject.state = .success
}
cell.disPlayCell(object: cell.downloadObject)
}
}
}
| apache-2.0 |
darkzero/DZPopupMessageView | Example/DZPopupMessageSample/AppDelegate.swift | 1 | 2183 | //
// AppDelegate.swift
// DZPopupMessageSample
//
// Created by Yuhua Hu on 2019/01/23.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
spark/photon-tinker-ios | Photon-Tinker/Global/Extensions/Comparable.swift | 1 | 286 | //
// Created by Raimundas Sakalauskas on 2019-08-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
| apache-2.0 |
amrap-labs/TeamupKit | Sources/TeamupKit/Environment/ApiEnvironment.swift | 1 | 477 | //
// ApiEnvironment.swift
// TeamupKit
//
// Created by Merrick Sapsford on 27/06/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import Foundation
/// Environment configuration for live API.
internal class ApiEnvironment: Environment {
var requestExecutorType: RequestExecutor.Type {
return ApiRequestExecutor.self
}
var controllerFactoryType: ControllerFactory.Type {
return ApiControllerFactory.self
}
}
| mit |
fellipecaetano/Democracy-iOS | Sources/Application/AppState.swift | 1 | 182 | struct AppState {
let politicians: PoliticiansState
let followedPoliticians: [Politician]
static let initial = AppState(politicians: .initial, followedPoliticians: [])
}
| mit |
RxSwiftCommunity/RxAnimated | Tests/RxAnimatedTests/XCTestManifests.swift | 1 | 111 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return []
}
#endif
| mit |
novi/proconapp | ProconApp/ProconManager/AppDelegate.swift | 1 | 2194 | //
// AppDelegate.swift
// ProconManager
//
// Created by ito on 2015/07/09.
// Copyright (c) 2015年 Procon. All rights reserved.
//
import UIKit
import ProconBase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
#if DEBUG
Logger.debug("debug flag is on")
#endif
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:.
}
}
| bsd-3-clause |
SteveBarnegren/SwiftChess | SwiftChess/SwiftChessTests/PieceTests.swift | 1 | 1681 | //
// PieceTests.swift
// Example
//
// Created by Steve Barnegren on 26/11/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
@testable import SwiftChess
class PieceTests: 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 testAllPiecesHaveUniqueTags() {
let board = Board(state: .newGame)
var foundTags = [Int]()
for square in board.squares {
guard let piece = square.piece else {
continue
}
XCTAssertFalse(foundTags.contains(piece.tag), "Expected all pieces to have unique tags")
foundTags.append(piece.tag)
}
}
// MARK: - DictionaryRepresentable
func testPieceDictionaryRepresentable() {
var piece1 = Piece(type: .pawn, color: .white)
piece1.tag = 0
piece1.hasMoved = false
piece1.canBeTakenByEnPassant = false
piece1.location = BoardLocation(index: 0)
XCTAssertEqual(piece1, piece1.toDictionaryAndBack)
var piece2 = Piece(type: .bishop, color: .black)
piece2.tag = 15
piece2.hasMoved = true
piece2.canBeTakenByEnPassant = true
piece2.location = BoardLocation(index: 15)
XCTAssertEqual(piece2, piece2.toDictionaryAndBack)
}
}
| mit |
lizhenning87/SwiftZhiHu | SwiftZhiHu/SwiftZhiHu/Haneke/Haneke.swift | 1 | 1369 | //
// Haneke.swift
// Haneke
//
// Created by Hermes Pique on 9/9/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public struct Haneke {
public static let Domain = "io.haneke"
public static func errorWithCode(code : Int, description : String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: description]
return NSError(domain: Haneke.Domain, code: code, userInfo: userInfo)
}
public static var sharedImageCache : Cache<UIImage> {
struct Static {
static let name = "shared-images"
static let cache = Cache<UIImage>(name: name)
}
return Static.cache
}
public static var sharedDataCache : Cache<NSData> {
struct Static {
static let name = "shared-data"
static let cache = Cache<NSData>(name: name)
}
return Static.cache
}
public static var sharedStringCache : Cache<String> {
struct Static {
static let name = "shared-strings"
static let cache = Cache<String>(name: name)
}
return Static.cache
}
public static var sharedJSONCache : Cache<JSON> {
struct Static {
static let name = "shared-json"
static let cache = Cache<JSON>(name: name)
}
return Static.cache
}
}
| apache-2.0 |
cornerstonecollege/402 | 402_2016_2/CustomViewMaps/CustomViewMaps/ViewController.swift | 1 | 1567 | //
// ViewController.swift
// CustomViewMaps
//
// Created by Luiz on 2016-11-08.
// Copyright © 2016 Ideia do Luiz. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let vancouverCoordinate = CLLocationCoordinate2D(latitude: 49.2827, longitude: -123.1207)
self.mapView.setRegion(MKCoordinateRegionMake(vancouverCoordinate, MKCoordinateSpanMake(1, 1)), animated: true)
self.mapView.delegate = self
// let annotation = MKPointAnnotation()
// annotation.coordinate = vancouverCoordinate
// annotation.title = "City of Vancouver"
// annotation.subtitle = "Hello all."
let annotation = CustomAnnotation(coordinate: vancouverCoordinate)
annotation.title = "Custom annotation title"
annotation.subtitle = "Custom annotation subtitle"
self.mapView.addAnnotation(annotation)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is CustomAnnotation {
let annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: "customIdentifier")
return annotationView
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
tlax/GaussSquad | GaussSquad/Model/LinearEquations/Solution/Items/MLinearEquationsSolutionEquationItemPolynomial.swift | 1 | 8068 | import UIKit
class MLinearEquationsSolutionEquationItemPolynomial:MLinearEquationsSolutionEquationItem
{
weak var indeterminate:MLinearEquationsSolutionIndeterminatesItem!
let coefficient:Double
let coefficientDividend:Double
let coefficientDivisor:Double
let showSign:Bool
let showAsDivision:Bool
init(
indeterminate:MLinearEquationsSolutionIndeterminatesItem,
coefficientDividend:Double,
coefficientDivisor:Double,
showSign:Bool,
showAsDivision:Bool,
reusableIdentifier:String,
cellWidth:CGFloat)
{
self.indeterminate = indeterminate
self.coefficientDividend = coefficientDividend
self.coefficientDivisor = coefficientDivisor
self.showSign = showSign
self.showAsDivision = showAsDivision
self.coefficient = coefficientDividend / coefficientDivisor
super.init(
reusableIdentifier:reusableIdentifier,
cellWidth:cellWidth)
}
//MARK: private
private func sum(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
changeSign:Bool,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let sumItem:MLinearEquationsSolutionEquationItemPolynomial
let otherPolynomialDivisor:Double = otherPolynomial.coefficientDivisor
let otherPolynomialDividend:Double
let sumDividend:Double
let sumDivisor:Double
if changeSign
{
otherPolynomialDividend = -otherPolynomial.coefficientDividend
}
else
{
otherPolynomialDividend = otherPolynomial.coefficientDividend
}
if coefficientDivisor == otherPolynomialDivisor
{
sumDividend = coefficientDividend + otherPolynomialDividend
sumDivisor = coefficientDivisor
}
else
{
let scaledDividend:Double = coefficientDividend * otherPolynomialDivisor
let scaledOtherPolynomialDividend:Double = otherPolynomialDividend * coefficientDivisor
sumDividend = scaledDividend + scaledOtherPolynomialDividend
sumDivisor = coefficientDivisor * otherPolynomialDivisor
}
let newCoefficient:Double = abs(sumDividend / sumDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
if self.showAsDivision || otherPolynomial.showAsDivision
{
showAsDivision = true
}
else
{
showAsDivision = false
}
}
else
{
showAsDivision = false
}
sumItem = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:sumDividend,
coefficientDivisor:sumDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
}
else
{
sumItem = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:newIndex)
}
return sumItem
}
//MARK: public
func add(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let addedItem:MLinearEquationsSolutionEquationItemPolynomial = sum(
otherPolynomial:otherPolynomial,
changeSign:false,
newIndex:newIndex)
return addedItem
}
func subtract(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let subtractedItem:MLinearEquationsSolutionEquationItemPolynomial = sum(
otherPolynomial:otherPolynomial,
changeSign:true,
newIndex:newIndex)
return subtractedItem
}
func inversed(newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let inversedPolynomial:MLinearEquationsSolutionEquationItemPolynomial = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:-coefficientDividend,
coefficientDivisor:coefficientDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
return inversedPolynomial
}
func multiply(
dividend:Double,
divisor:Double,
index:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let multiplied:MLinearEquationsSolutionEquationItemPolynomial
let newDividend:Double = coefficientDividend * dividend
let newDivisor:Double = coefficientDivisor * divisor
let newCoefficient:Double = abs(newDividend / newDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
showAsDivision = self.showAsDivision
}
else
{
showAsDivision = false
}
multiplied = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:newDividend,
coefficientDivisor:newDivisor,
indeterminate:indeterminate,
index:index,
showAsDivision:showAsDivision)
}
else
{
multiplied = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:index)
}
return multiplied
}
func divide(
dividend:Double,
divisor:Double,
index:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let divided:MLinearEquationsSolutionEquationItemPolynomial
let newDividend:Double = coefficientDividend / dividend
let newDivisor:Double = coefficientDivisor / divisor
let newCoefficient:Double = abs(newDividend / newDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
showAsDivision = self.showAsDivision
}
else
{
showAsDivision = false
}
divided = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:newDividend,
coefficientDivisor:newDivisor,
indeterminate:indeterminate,
index:index,
showAsDivision:showAsDivision)
}
else
{
divided = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:index)
}
return divided
}
func reIndexed(newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let indexedPolynomial:MLinearEquationsSolutionEquationItemPolynomial = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:coefficientDividend,
coefficientDivisor:coefficientDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
return indexedPolynomial
}
}
| mit |
343max/WorldTime | WorldTimeTodayWidget/TodayViewController.swift | 1 | 2814 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var collectionView: UICollectionView!
var collectionViewSource = LocationsCollectionViewDataSource()
var minuteChangeNotifier: MinuteChangeNotifier?
override func viewDidLoad() {
self.view.backgroundColor = UIColor.clear
collectionView.backgroundColor = UIColor.clear
collectionViewSource.prepare(collectionView: collectionView)
setup()
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setup()
self.minuteChangeNotifier = MinuteChangeNotifier(delegate: self)
self.timeHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.timeHidden = true
self.minuteChangeNotifier = nil
}
func setup() {
let locations = Location.fromDefaults()
collectionViewSource.locations = locations
collectionView.reloadData()
guard let layout = collectionView.collectionViewLayout as? WorldTimeLayout else {
fatalError("not a WorldTimeLayout")
}
extensionContext?.widgetLargestAvailableDisplayMode = locations.count <= maximumLocationsCompactMode() ? .compact : .expanded
layout.prepareLayout(itemCount: collectionViewSource.locations.count)
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
guard let layout = collectionView.collectionViewLayout as? WorldTimeLayout else {
fatalError("not a WorldTimeLayout")
}
layout.minContentHeight = activeDisplayMode == .compact ? maxSize.height : nil
preferredContentSize = CGSize(width: 0, height: min(maxSize.height, layout.perfectContentHeight))
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
completionHandler(NCUpdateResult.newData)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.collectionView.frame = self.view.bounds
}
var timeHidden: Bool = false {
didSet(oldTimeHidden) {
collectionViewSource.timeHidden = timeHidden
collectionView.reloadData()
}
}
}
extension TodayViewController: MinuteChangeNotifierDelegate {
func minuteDidChange(notifier: MinuteChangeNotifier) {
for cell in collectionView.visibleCells {
if let cell = cell as? TimeZoneCollectionViewCell {
cell.update()
}
}
}
}
| mit |
mpclarkson/fluent-example | Package.swift | 1 | 373 | import PackageDescription
let package = Package(
name: "FluentApp",
dependencies: [
//.Package(url: "https://github.com/tannernelson/vapor.git", majorVersion: 0),
.Package(url: "https://github.com/tannernelson/fluent.git", majorVersion: 0),
.Package(url: "https://github.com/tannernelson/fluent-sqlite-driver.git", majorVersion: 0),
]
) | mit |
albert438/JSPatch | Demo/SwiftDemo/SwiftDemo/AppDelegate.swift | 3 | 2979 | //
// AppDelegate.swift
// SwiftDemo
//
// Created by KouArlen on 16/2/3.
// Copyright © 2016年 Arlen. 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.
let aClass: AnyClass? = NSClassFromString("SwiftDemo.ViewController")
if (aClass != nil) {
let clsName = NSStringFromClass(aClass!)
print(clsName)
} else {
print("error ViewController not found")
}
let bClass: AnyClass? = NSClassFromString("SwiftDemo.TestObject")
if (bClass != nil) {
let clsName = NSStringFromClass(bClass!)
print(clsName)
} else {
print("error TestObject not found")
}
let path = NSBundle.mainBundle().pathForResource("demo", ofType: "js")
do {
let patch = try String(contentsOfFile: path!)
JPEngine.startEngine()
JPEngine.evaluateScript(patch)
} catch {}
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 |
mdznr/Keyboard | KeyboardExtension/Keyboard.swift | 1 | 6400 | //
// Keyboard.swift
// Keyboard
//
// Created by Matt Zanchelli on 6/19/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
protocol KeyboardDelegate {
func keyboard(keyboard: Keyboard, didSelectKey key: KeyboardKey)
}
class Keyboard: UIControl {
// MARK: Initialization
convenience override init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.autoresizingMask = .FlexibleWidth | .FlexibleHeight
self.multipleTouchEnabled = true
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Properties
/// An array of rows (an array) of keys.
var keys: [[KeyboardKey]] = [[]] {
willSet {
// Remove all layout constraints.
self.removeConstraints(self.constraints())
// Remove all the rows from the view.
for view in self.subviews as [UIView] {
view.removeFromSuperview()
}
}
didSet {
var rows = Dictionary<String, UIView>()
var previousView: UIView = self
for x in 0..<keys.count {
let rowOfKeys = keys[x]
let row = Keyboard.createRow()
let rowName = "row" + x.description
rows[rowName] = row // rows.updateValue(row, forKey: rowName)
self.addSubview(row)
row.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[row]|", options: nil, metrics: nil, views: ["row": row]))
let attribute: NSLayoutAttribute = (x == 0) ? .Top : .Bottom
self.addConstraint(NSLayoutConstraint(item: row, attribute: .Top, relatedBy: .Equal, toItem: previousView, attribute: attribute, multiplier: 1, constant: 0))
previousView = row
self.addConstraint(NSLayoutConstraint(item: row, attribute: .Height, relatedBy: .Equal, toItem: row.superview, attribute: .Height, multiplier: rowHeights[x], constant: 0))
let metrics = ["top": edgeInsets[x].top, "bottom": edgeInsets[x].bottom]
var horizontalVisualFormatString = "H:|-(\(edgeInsets[x].left))-"
var views = Dictionary<String, UIView>()
var firstEquallySizedView = -1
for i in 0..<rowOfKeys.count {
let view = rowOfKeys[i]
let viewName = "view" + i.description
views.updateValue(view, forKey: viewName)
row.addSubview(view)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(top)-[view]-(bottom)-|", options: nil, metrics: metrics, views: ["view": view]))
let contentSize = view.intrinsicContentSize()
if contentSize.width == UIViewNoIntrinsicMetric {
if firstEquallySizedView < 0 {
firstEquallySizedView = i
horizontalVisualFormatString += "[\(viewName)]"
} else {
horizontalVisualFormatString += "[\(viewName)(==view\(firstEquallySizedView.description))]"
}
} else {
horizontalVisualFormatString += "[\(viewName)]"
}
}
horizontalVisualFormatString += "-(\(edgeInsets[x].right))-|"
if views.count > 0 {
row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormatString, options: nil, metrics: nil, views: views))
}
}
}
}
/// The edge insets for each row.
var edgeInsets: [UIEdgeInsets] = []
/// The heights for each row.
var rowHeights: [CGFloat] = []
// MARK: Helper functions
class func createRow() -> UIView {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let divider = KeyboardDivider()
view.addSubview(divider)
let views = ["divider": divider]
divider.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[divider]|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[divider(0.5)]", options: nil, metrics: nil, views: views))
return view
}
// MARK: Gesture handling
var touchesToViews = Dictionary<UITouch, UIView>()
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = self.hitTest(touch.locationInView(self), withEvent: event)
touchesToViews[touch] = view
if let view = view as? KeyboardKey {
view.highlighted = true
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = self.hitTest(touch.locationInView(self), withEvent: event)
let previousView = touchesToViews[touch]
if view != previousView {
if let previousView = previousView as? KeyboardKey {
previousView.highlighted = false
}
touchesToViews[touch] = view
if let view = view as? KeyboardKey {
view.highlighted = true
}
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = touchesToViews[touch]
if let view = view as? KeyboardKey {
view.highlighted = false
view.didSelect()
}
touchesToViews.removeValueForKey(touch)
}
}
override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = touchesToViews[touch]
if let view = view as? KeyboardKey {
view.highlighted = false
}
touchesToViews.removeValueForKey(touch)
}
}
}
class KeyboardKey: UIView {
/// A Boolean value represeting whether the key is highlighted (a touch is inside).
var highlighted: Bool = false
// What to do when this is selected.
var action: () -> () = {}
override init(frame: CGRect) {
super.init(frame: frame)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Called when a key has been selected. Subclasses can use this to present differently. Must call super!
func didSelect() {
action()
}
}
class KeyboardDivider: UIView {
convenience override init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.backgroundColor = KeyboardAppearance.dividerColorForAppearance(UIKeyboardAppearance.Default)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit |
tombuildsstuff/swiftcity | SwiftCity/Entities/SnapshotDependencies.swift | 1 | 834 | public struct SnapshotDependencies {
public let count: Int
public let dependencies: [SnapshotDependency]
init?(dictionary: [String: AnyObject]) {
guard let count = dictionary["count"] as? Int,
let dependenciesDictionary = dictionary["snapshot-dependency"] as? [[String: AnyObject]] else {
return nil
}
let dependencies = dependenciesDictionary.map { (dictionary: [String : AnyObject]) -> SnapshotDependency? in
return SnapshotDependency(dictionary: dictionary)
}.filter { (dependency: SnapshotDependency?) -> Bool in
return dependency != nil
}.map { (dependency: SnapshotDependency?) -> SnapshotDependency in
return dependency!
}
self.count = count
self.dependencies = dependencies
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/20487-no-stacktrace.swift | 11 | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
return m ( {
let f = [ {
enum b { func c {
struct B {
protocol A {
class
case ,
| mit |
ello/ello-ios | Sources/Model/Love.swift | 1 | 2018 | ////
/// Love.swift
//
import SwiftyJSON
let LoveVersion: Int = 1
@objc(Love)
final class Love: Model, PostActionable {
let id: String
var isDeleted: Bool
let postId: String
let userId: String
var post: Post? { return getLinkObject("post") }
var user: User? { return getLinkObject("user") }
init(
id: String,
isDeleted: Bool,
postId: String,
userId: String
) {
self.id = id
self.isDeleted = isDeleted
self.postId = postId
self.userId = userId
super.init(version: LoveVersion)
addLinkObject("post", id: postId, type: .postsType)
addLinkObject("user", id: userId, type: .usersType)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.id = decoder.decodeKey("id")
self.isDeleted = decoder.decodeKey("deleted")
self.postId = decoder.decodeKey("postId")
self.userId = decoder.decodeKey("userId")
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(id, forKey: "id")
coder.encodeObject(isDeleted, forKey: "deleted")
coder.encodeObject(postId, forKey: "postId")
coder.encodeObject(userId, forKey: "userId")
super.encode(with: coder.coder)
}
class func fromJSON(_ data: [String: Any]) -> Love {
let json = JSON(data)
let love = Love(
id: json["id"].idValue,
isDeleted: json["deleted"].boolValue,
postId: json["post_id"].stringValue,
userId: json["user_id"].stringValue
)
love.mergeLinks(data["links"] as? [String: Any])
love.addLinkObject("post", id: love.postId, type: .postsType)
love.addLinkObject("user", id: love.userId, type: .usersType)
return love
}
}
extension Love: JSONSaveable {
var uniqueId: String? { return "Love-\(id)" }
var tableId: String? { return id }
}
| mit |
austinzheng/swift-compiler-crashes | fixed/26023-swift-createimplicitconstructor.swift | 7 | 229 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A{
protocol B:s}extension String{
let h=j
struct A
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/23984-llvm-foldingset-swift-classtype-nodeequals.swift | 9 | 250 | // 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
protocol a{
func b{
}
func a
class a{class c}
class b<T where B:b{func
p
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/18797-resolvetypedecl.swift | 11 | 273 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
class a<T where g: BooleanType
class A {
{
{
{
{
}
}
{
{
}
}
{
}
}
}
{
}
struct A {
var d = a
| mit |
naddison36/book-review-ios | Pods/RSBarcodes_Swift/Source/RSCodeReaderViewController.swift | 1 | 10986 | //
// RSCodeReaderViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/12/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
public class RSCodeReaderViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
public lazy var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
public lazy var output = AVCaptureMetadataOutput()
public lazy var session = AVCaptureSession()
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
public lazy var focusMarkLayer = RSFocusMarkLayer()
public lazy var cornersLayer = RSCornersLayer()
public var tapHandler: ((CGPoint) -> Void)?
public var barcodesHandler: ((Array<AVMetadataMachineReadableCodeObject>) -> Void)?
var ticker: NSTimer?
public var isCrazyMode = false
var isCrazyModeStarted = false
var lensPosition: Float = 0
// MARK: Public methods
public func hasFlash() -> Bool {
if let d = self.device {
return d.hasFlash
}
return false
}
public func hasTorch() -> Bool {
if let d = self.device {
return d.hasTorch
}
return false
}
public func toggleTorch() -> Bool {
if self.hasTorch() {
self.session.beginConfiguration()
self.device.lockForConfiguration(nil)
if self.device.torchMode == .Off {
self.device.torchMode = .On
} else if self.device.torchMode == .On {
self.device.torchMode = .Off
}
self.device.unlockForConfiguration()
self.session.commitConfiguration()
return self.device.torchMode == .On
}
return false
}
// MARK: Private methods
class func interfaceOrientationToVideoOrientation(orientation : UIInterfaceOrientation) -> AVCaptureVideoOrientation {
switch (orientation) {
case .Unknown:
fallthrough
case .Portrait:
return AVCaptureVideoOrientation.Portrait
case .PortraitUpsideDown:
return AVCaptureVideoOrientation.PortraitUpsideDown
case .LandscapeLeft:
return AVCaptureVideoOrientation.LandscapeLeft
case .LandscapeRight:
return AVCaptureVideoOrientation.LandscapeRight
}
}
func autoUpdateLensPosition() {
self.lensPosition += 0.01
if self.lensPosition > 1 {
self.lensPosition = 0
}
if device.lockForConfiguration(nil) {
self.device.setFocusModeLockedWithLensPosition(self.lensPosition, completionHandler: nil)
device.unlockForConfiguration()
}
if session.running {
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(USEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue(), {
self.autoUpdateLensPosition()
})
}
}
func onTick() {
if let t = self.ticker {
t.invalidate()
}
self.cornersLayer.cornersArray = []
}
func onTap(gesture: UITapGestureRecognizer) {
let tapPoint = gesture.locationInView(self.view)
let focusPoint = CGPointMake(
tapPoint.x / self.view.bounds.size.width,
tapPoint.y / self.view.bounds.size.height)
if let d = self.device {
if d.lockForConfiguration(nil) {
if d.focusPointOfInterestSupported {
d.focusPointOfInterest = focusPoint
} else {
println("Focus point of interest not supported.")
}
if self.isCrazyMode {
if d.isFocusModeSupported(.Locked) {
d.focusMode = .Locked
} else {
println("Locked focus not supported.")
}
if !self.isCrazyModeStarted {
self.isCrazyModeStarted = true
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.autoUpdateLensPosition()
})
}
} else {
if d.isFocusModeSupported(.ContinuousAutoFocus) {
d.focusMode = .ContinuousAutoFocus
} else if d.isFocusModeSupported(.AutoFocus) {
d.focusMode = .AutoFocus
} else {
println("Auto focus not supported.")
}
}
if d.autoFocusRangeRestrictionSupported {
d.autoFocusRangeRestriction = .None
} else {
println("Auto focus range restriction not supported.")
}
d.unlockForConfiguration()
self.focusMarkLayer.point = tapPoint
}
}
if let h = self.tapHandler {
h(tapPoint)
}
}
func onApplicationWillEnterForeground() {
self.session.startRunning()
}
func onApplicationDidEnterBackground() {
self.session.stopRunning()
}
// MARK: Deinitialization
deinit {
println("RSCodeReaderViewController deinit")
}
// MARK: View lifecycle
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let l = self.videoPreviewLayer {
let videoOrientation = RSCodeReaderViewController.interfaceOrientationToVideoOrientation(UIApplication.sharedApplication().statusBarOrientation)
if l.connection.supportsVideoOrientation
&& l.connection.videoOrientation != videoOrientation {
l.connection.videoOrientation = videoOrientation
}
}
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let frame = CGRectMake(0, 0, size.width, size.height)
if let l = self.videoPreviewLayer {
l.frame = frame
}
if let l = self.focusMarkLayer {
l.frame = frame
}
if let l = self.cornersLayer {
l.frame = frame
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
var error : NSError?
let input = AVCaptureDeviceInput(device: self.device, error: &error)
if let e = error {
println(e.description)
return
}
if let d = self.device {
if d.lockForConfiguration(nil) {
if self.device.isFocusModeSupported(.ContinuousAutoFocus) {
self.device.focusMode = .ContinuousAutoFocus
}
if self.device.autoFocusRangeRestrictionSupported {
self.device.autoFocusRangeRestriction = .Near
}
self.device.unlockForConfiguration()
}
}
if self.session.canAddInput(input) {
self.session.addInput(input)
}
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
if let l = self.videoPreviewLayer {
l.videoGravity = AVLayerVideoGravityResizeAspectFill
l.frame = self.view.bounds
self.view.layer.addSublayer(l)
}
let queue = dispatch_queue_create("com.pdq.rsbarcodes.metadata", DISPATCH_QUEUE_CONCURRENT)
self.output.setMetadataObjectsDelegate(self, queue: queue)
if self.session.canAddOutput(self.output) {
self.session.addOutput(self.output)
self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onTap:")
self.view.addGestureRecognizer(tapGestureRecognizer)
self.focusMarkLayer.frame = self.view.bounds
self.view.layer.addSublayer(self.focusMarkLayer)
self.cornersLayer.frame = self.view.bounds
self.view.layer.addSublayer(self.cornersLayer)
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationWillEnterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
self.session.startRunning()
}
override public func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)
self.session.stopRunning()
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var barcodeObjects : Array<AVMetadataMachineReadableCodeObject> = []
var cornersArray : Array<[AnyObject]> = []
for metadataObject : AnyObject in metadataObjects {
if let l = self.videoPreviewLayer {
let transformedMetadataObject = l.transformedMetadataObjectForMetadataObject(metadataObject as! AVMetadataObject)
if transformedMetadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject.self) {
let barcodeObject = transformedMetadataObject as! AVMetadataMachineReadableCodeObject
barcodeObjects.append(barcodeObject)
cornersArray.append(barcodeObject.corners)
}
}
}
self.cornersLayer.cornersArray = cornersArray
if barcodeObjects.count > 0 {
if let h = self.barcodesHandler {
h(barcodeObjects)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let t = self.ticker {
t.invalidate()
}
self.ticker = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "onTick", userInfo: nil, repeats: true)
})
}
}
| mit |
CatchChat/Yep | Yep/ViewControllers/Show/ShowStepGeniusViewController.swift | 1 | 2903 | //
// ShowStepGeniusViewController.swift
// Yep
//
// Created by nixzhu on 15/8/20.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class ShowStepGeniusViewController: ShowStepViewController {
@IBOutlet private weak var rightPurpleDot: UIImageView!
@IBOutlet private weak var leftGreenDot: UIImageView!
@IBOutlet private weak var leftBlueDot: UIImageView!
@IBOutlet private weak var leftRedDot: UIImageView!
@IBOutlet private weak var leftPurpleDot: UIImageView!
@IBOutlet private weak var topRedDot: UIImageView!
@IBOutlet private weak var rightBlueDot: UIImageView!
@IBOutlet private weak var centerBlueDot: UIImageView!
@IBOutlet private weak var centerOrangeDot: UIImageView!
@IBOutlet private weak var rightYellowDot: UIImageView!
@IBOutlet private weak var rightGreenDot: UIImageView!
@IBOutlet private weak var dotsLink: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = NSLocalizedString("Genius", comment: "")
subTitleLabel.text = NSLocalizedString("Discover them around you", comment: "")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
repeatAnimate(rightPurpleDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(rightPurpleDot.frame, 2, 2)), duration: 4)
repeatAnimate(leftGreenDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(leftGreenDot.frame, 5, 5)), duration: 2.5)
repeatAnimate(leftBlueDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(leftBlueDot.frame, 3, 3)), duration: 4)
repeatAnimate(leftRedDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(leftRedDot.frame, 3, 3)), duration: 1.5)
repeatAnimate(leftPurpleDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(leftPurpleDot.frame, 1, 1)), duration: 6)
repeatAnimate(topRedDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(topRedDot.frame, 1, 1)), duration: 2)
repeatAnimate(rightBlueDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(rightBlueDot.frame, 1, 1)), duration: 3)
repeatAnimate(centerBlueDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(centerBlueDot.frame, 1, 1)), duration: 3)
repeatAnimate(centerOrangeDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(centerOrangeDot.frame, 1, 1)), duration: 3)
repeatAnimate(rightYellowDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(rightYellowDot.frame, 1, 1)), duration: 3)
repeatAnimate(rightGreenDot, alongWithPath: UIBezierPath(ovalInRect: CGRectInset(rightGreenDot.frame, 1, 1)), duration: 3)
let dotsLinkPath = UIBezierPath(arcCenter: dotsLink.center, radius: 5, startAngle: 0, endAngle: 2, clockwise: false)
repeatAnimate(dotsLink, alongWithPath: dotsLinkPath, duration: 7, autoreverses: true)
}
}
| mit |
raymondshadow/SwiftDemo | SwiftApp/StudyNote/StudyNote/ScrollView/SNTableViewSummaryController.swift | 1 | 4293 | //
// SNTableViewSummaryController.swift
// StudyNote
//
// Created by wuyp on 2019/6/24.
// Copyright © 2019 Raymond. All rights reserved.
//
import UIKit
import Common
private let kCellID = String(describing: UITableViewCell.self)
class SNTableViewSummaryController: UIViewController {
@objc private lazy dynamic var table: UITableView = {
let tableview = UITableView(frame: self.view.bounds, style: .grouped)
tableview.backgroundColor = UIColor.purple
tableview.frame = CGRect(x: 0, y: kNavigationStatuBarHeight, width: kScreenWidth, height: kScreenHeight - kNavigationStatuBarHeight - kBottomSafeHeight)
tableview.delegate = self
tableview.dataSource = self
tableview.register(UITableViewCell.self, forCellReuseIdentifier: kCellID)
tableview.register(SNNormalTextCell.self, forCellReuseIdentifier: "SNNormalTextCell")
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tabTapAction))
// tapGesture.delegate = self
tapGesture.cancelsTouchesInView = false
tableview.addGestureRecognizer(tapGesture)
if #available(iOS 11, *) {
tableview.contentInsetAdjustmentBehavior = .never
tableview.contentInset = .zero
}
return tableview
}()
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(table)
}
}
extension SNTableViewSummaryController: UITableViewDelegate, UITableViewDataSource {
@objc dynamic func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@objc dynamic func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 25
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
@objc dynamic func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
@objc dynamic func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SNNormalTextCell", for: indexPath)
// setCellContent(row: indexPath.row, cell: cell)
return cell
}
@objc private dynamic func setCellContent(row: Int, cell: UITableViewCell) {
switch row {
case 0:
let btn = UIButton(frame: CGRect(x: 15, y: 10, width: 100, height: 30))
btn.setTitle("测试", for: .normal)
btn.setTitleColor(.purple, for: .normal)
btn.addTarget(self, action: #selector(cellBtnClickAction), for: .touchUpInside)
cell.contentView.addSubview(btn)
break
case 1:
let tf = UITextField(frame: CGRect(x: 15, y: 10, width: 150, height: 30))
tf.placeholder = "请输入"
cell.contentView.addSubview(tf)
break
default:
cell.textLabel?.text = "Row \(row)"
break
}
}
}
extension SNTableViewSummaryController {
@objc private dynamic func cellBtnClickAction() {
print("----click button")
}
@objc private dynamic func tabTapAction() {
self.view.endEditing(true)
}
}
extension SNTableViewSummaryController: UIGestureRecognizerDelegate {
@objc dynamic func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard let touchView = touch.view else { return true }
return true
}
}
extension CaseIterable where Self: RawRepresentable {
static var allValues: [RawValue] {
return self.allCases.map{ $0.rawValue }
}
static var allTypes: [Self] {
return self.allCases.map{ $0 }
}
}
extension SNTableViewSummaryController: SNRouteInterruptHandleProtocol {
static func handleRoute(route: SNRouteEntity) -> SNRouteFlowResult {
print("SNTableViewSummaryController load interrupt")
return .stop
}
}
| apache-2.0 |
martinjakubik/war | batanimal/AppDelegate.swift | 1 | 454 | //
// AppDelegate.swift
// batanimal
//
// Created by Marcin Jakubik on 20/02/18.
// Copyright © 2018 martin jakubik. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| apache-2.0 |
yq616775291/DiliDili-Fun | DiliDili/Classes/Home/ViewController/RecommendViewController.swift | 1 | 955 | //
// RecommendViewController.swift
// DiliDili
//
// Created by yq on 16/3/9.
// Copyright © 2016年 yq. All rights reserved.
//
import UIKit
class RecommendViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.yellowColor()
// Do any additional setup after loading the view.
self.title = "推荐"
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
qvacua/vimr | Tabs/Support/TabsSupport/AppDelegate.swift | 1 | 2082 | //
// AppDelegate.swift
// TabsSupport
//
// Created by Tae Won Ha on 22.11.20.
//
import Cocoa
import PureLayout
import Tabs
@main
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow!
override init() {
self.tabBar = TabBar(withTheme: .default)
super.init()
}
func applicationDidFinishLaunching(_: Notification) {
let contentView = self.window.contentView!
contentView.addSubview(self.tabBar)
let tb = self.tabBar
tb.autoPinEdge(toSuperviewEdge: .top)
tb.autoPinEdge(toSuperviewEdge: .left)
tb.autoPinEdge(toSuperviewEdge: .right)
tb.autoSetDimension(.height, toSize: Theme().tabBarHeight)
tb.selectHandler = { [weak self] _, selectedEntry, _ in
self?.tabEntries.enumerated().forEach { index, entry in
self?.tabEntries[index].isSelected = (entry == selectedEntry)
}
DispatchQueue.main.async {
Swift.print("select: \(self!.tabEntries)")
self?.tabBar.update(tabRepresentatives: self?.tabEntries ?? [])
}
}
tb.reorderHandler = { [weak self] index, reorderedEntry, entries in
self?.tabEntries = entries
self?.tabEntries.enumerated().forEach { index, entry in
self?.tabEntries[index].isSelected = (entry == reorderedEntry)
}
DispatchQueue.main.async {
Swift.print("reorder: \(entries)")
self?.tabBar.update(tabRepresentatives: self?.tabEntries ?? [])
}
}
self.tabEntries = [
DummyTabEntry(title: "Test 1"),
DummyTabEntry(title: "Test 2"),
DummyTabEntry(title: "Test 3"),
DummyTabEntry(title: "Very long long long title, and some more text!"),
]
self.tabEntries[0].isSelected = true
self.tabBar.update(tabRepresentatives: self.tabEntries)
}
func applicationWillTerminate(_: Notification) {
// Insert code here to tear down your application
}
private let tabBar: TabBar<DummyTabEntry>
private var tabEntries = [DummyTabEntry]()
}
struct DummyTabEntry: Hashable, TabRepresentative {
var title: String
var isSelected = false
}
| mit |
benwwchen/sysujwxt-ios | SYSUJwxt/GradeViewController.swift | 1 | 5052 | //
// GradeViewController.swift
// SYSUJwxt
//
// Created by benwwchen on 2017/8/17.
// Copyright © 2017年 benwwchen. All rights reserved.
//
import UIKit
class GradeViewController: ListWithFilterViewController,
UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var gradesTableView: UITableView!
// MARK: Properties
var grades = [Grade]()
// MARK: Methods
override func loadData(completion: (() -> Void)? = nil) {
loadSavedFilterData()
var isGetAll = false
var isGetAllTerms = false
var yearInt: Int = 0
var termInt: Int = 0
if self.year == "全部" {
isGetAll = true
} else {
yearInt = Int(self.year.components(separatedBy: "-")[0])!
}
if self.term == "全部" {
isGetAllTerms = true
} else {
termInt = Int(self.term)!
}
let coursesTypeValues = coursesType.map({ CourseType.fromString(string: $0) })
jwxt.getGradeList(year: yearInt, term: termInt, isGetAll: isGetAll, isGetAllTerms: isGetAllTerms) { (success, object) in
if success, let grades = object as? [Grade] {
self.grades.removeAll()
// filter a courseType and append to the table data
let filteredGrades = grades.filter({ coursesTypeValues.contains($0.courseType) })
let sortedFilteredGrades = filteredGrades.sorted(by: { (grade1, grade2) -> Bool in
if grade1.year > grade2.year {
return true
} else if grade1.year == grade2.year {
if grade1.term > grade2.term {
return true
} else if grade1.term == grade2.term {
return grade1.name > grade2.name
}
}
return false
})
self.grades.append(contentsOf: sortedFilteredGrades)
DispatchQueue.main.async {
self.gradesTableView.reloadData()
completion?()
}
}
}
}
// MARK: Table Views
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return grades.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "GradeTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? GradeTableViewCell else {
fatalError("The dequeued cell is not an instance of GradeTableViewCell.")
}
// populate the data
let grade = grades[indexPath.row]
cell.courseNameLabel.text = grade.name
cell.creditLabel.text = "\(grade.credit)"
cell.gpaLabel.text = "\(grade.gpa)"
cell.gradeLabel.text = "\(grade.totalGrade)"
cell.rankingInTeachingClassLabel.text = grade.rankingInTeachingClass
cell.rankingInMajorClassLabel.text = grade.rankingInMajorClass
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.setSelected(false, animated: true)
cell.isSelected = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl(tableView: gradesTableView)
gradesTableView.dataSource = self
gradesTableView.delegate = self
headerTitle = "成绩"
filterType = .grade
initSetup()
}
override func unwindToMainViewController(sender: UIStoryboardSegue) {
super.unwindToMainViewController(sender: sender)
if sender.source is UINavigationController {
print("nav")
}
if sender.source is NotifySettingTableViewController {
print("notify")
}
// save current grades if notification is on
if let _ = (sender.source as? UINavigationController)?.topViewController as? NotifySettingTableViewController,
let year = UserDefaults.standard.string(forKey: "notify.year"),
let yearInt = Int(year.components(separatedBy: "-")[0]),
let term = UserDefaults.standard.string(forKey: "notify.term") {
// save current grades
jwxt.getGradeList(year: yearInt, term: Int(term)!, completion: { (success, object) in
if success, let grades = object as? [Grade] {
UserDefaults.standard.set(grades, forKey: "monitorGrades")
}
})
isUnwindingFromFilter = false
}
}
}
| bsd-3-clause |
Dhvl-Golakiya/DGSwiftExtension | Pod/Classes/UILabelExtension.swift | 1 | 2957 | //
// Created by Dhvl Golakiya on 02/04/16.
// Copyright (c) 2016 Dhvl Golakiya. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
// Get Estimated size
public func getEstimatedSize(_ width: CGFloat = CGFloat.greatestFiniteMagnitude, height: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
return sizeThatFits(CGSize(width: width, height: height))
}
// Get Estimated Height
public func getEstimatedHeight() -> CGFloat {
return sizeThatFits(CGSize(width: self.getWidth, height: CGFloat.greatestFiniteMagnitude)).height
}
// Get Estimated width
public func getEstimatedWidth() -> CGFloat {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: self.getHeight)).width
}
// Set Label Height
public func fitHeight() {
self.setHeight(getEstimatedHeight())
}
// Set Label width
public func fitWidth() {
self.setWidth(getEstimatedWidth())
}
// Sel Label SIze
public func fitSize() {
self.fitWidth()
self.fitHeight()
sizeToFit()
}
// // Get line text in Array of String
public func getLinesArrayOfString() -> [String] {
let text:NSString = self.text! as NSString
let font:UIFont = self.font
let rect:CGRect = self.frame
self.lineBreakMode = .byWordWrapping
let myFont:CTFont = CTFontCreateWithName(font.fontName as CFString?, font.pointSize, nil)
let attStr:NSMutableAttributedString = NSMutableAttributedString(string: text as String)
attStr.addAttribute(String(kCTFontAttributeName), value:myFont, range: NSMakeRange(0, attStr.length))
let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path:CGMutablePath = CGMutablePath()
// path.move(to: CGPoint (x: getScreenWidth() - 40, y: 100000))
path.addRect(CGRect(x: 0, y: 0, width: getScreenWidth() - 30 , height: 100000))
// CGPathAddRect(path, nil, CGRect(x: 0, y: 0, width: getScreenWidth() - 40 , height: 100000))
let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame) as NSArray
var linesArray = [String]()
for line in lines {
let lineRange = CTLineGetStringRange(line as! CTLine)
let range:NSRange = NSMakeRange(lineRange.location, lineRange.length)
let lineString = text.substring(with: range)
linesArray.append(lineString as String)
}
return linesArray
}
// Get specif line text
public func getLinesArrayOfString(_ lineNumber : Int) -> String {
let lines = self.getLinesArrayOfString()
if lineNumber <= lines.count {
return lines[lineNumber]
}
return ""
}
}
| mit |
apple/swift | validation-test/compiler_crashers_fixed/26518-swift-diagnosticengine-flushactivediagnostic.swift | 65 | 461 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class a{struct Q<T where h:p{struct B{struct a{class A{let f=(
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/08664-swift-sourcemanager-getmessage.swift | 11 | 245 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension A {
var f = {
func f {
object (
{
class A {
enum b {
class
case ,
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/24767-llvm-foldingset-swift-enumtype-nodeequals.swift | 9 | 221 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let i{class d<T where B:r enum k{class a}enum S<l:d
| mit |
congncif/PagingDataController | Example/Pods/SiFUtilities/Localize/UINavigationItem+Localize.swift | 1 | 1088 | //
// UINavigationItem+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
@IBDesignable extension UINavigationItem: AssociatedObject {
@IBInspectable public var titleLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedTitleKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedTitleKey)
}
}
@IBInspectable public var backTitleLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedBackTitleKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedBackTitleKey)
}
}
@objc open override func updateLocalize() {
if let value = titleLocalizedKey, !titleLocalizedKey.isNoValue {
title = value.localized
}
if let value = backTitleLocalizedKey, !backTitleLocalizedKey.isNoValue {
backBarButtonItem?.title = value.localized
}
}
}
| mit |
jemmons/SessionArtist | Sources/SessionArtist/ValidJSONObject.swift | 1 | 275 | import Foundation
public struct ValidJSONObject {
public let value: JSONObject
public init(_ jsonObject: JSONObject) throws {
guard JSONSerialization.isValidJSONObject(jsonObject) else {
throw Error.invalidJSONObject
}
value = jsonObject
}
}
| mit |
LuAndreCast/iOS_WatchProjects | watchOS3/App Launching/AppLaunching/ViewController.swift | 1 | 501 | //
// ViewController.swift
// AppLaunching
//
// Created by Luis Castillo on 9/9/16.
// Copyright © 2016 LC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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 |
antonio081014/LeetCode-CodeBase | Swift/design-hashset.swift | 1 | 872 | class MyHashSet {
private var visited: [Bool]
private var length: Int
init() {
self.visited = []
self.length = 0
}
// - Complexity:
// - Time: O(n),
func add(_ key: Int) {
if key >= self.length {
self.visited += Array(repeating: false, count: key - visited.count + 1)
self.length = key + 1
}
visited[key] = true
}
func remove(_ key: Int) {
if key < self.length {
visited[key] = false
}
}
func contains(_ key: Int) -> Bool {
if key < self.length {
return visited[key]
}
return false
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* let obj = MyHashSet()
* obj.add(key)
* obj.remove(key)
* let ret_3: Bool = obj.contains(key)
*/
| mit |
CharlesVu/Smart-iPad | Tests/LinuxMain.swift | 1 | 122 | import XCTest
import Smart_iPadTests
var tests = [XCTestCaseEntry]()
tests += Smart_iPadTests.allTests()
XCTMain(tests)
| mit |
treejames/firefox-ios | Client/Frontend/Settings/SettingsTableViewController.swift | 2 | 39520 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Base32
import Shared
import UIKit
import XCGLogger
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var cell: UITableViewCell?
private var _title: NSAttributedString?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
let settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign in", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
private class SyncNowSetting: WithAccountSetting {
private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
private let log = Logger.browserLogger
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var style: UITableViewCellStyle { return .Value1 }
override var title: NSAttributedString? {
return syncNowTitle
}
override func onConfigureCell(cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
self.cell = cell
}
override func onClick(navigationController: UINavigationController?) {
if let cell = self.cell {
cell.userInteractionEnabled = false
cell.textLabel?.attributedText = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
profile.syncManager.syncEverything().uponQueue(dispatch_get_main_queue()) { result in
if result.isSuccess {
self.log.debug("Sync succeeded.")
} else {
self.log.debug("Sync failed.")
}
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
cell.textLabel?.attributedText = self.syncNowTitle
cell.userInteractionEnabled = true
})
}
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
if let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) {
cs.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs.URL
}
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// For great debugging!
private class HiddenSetting: Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
private class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
let browserDB = documentsPath.stringByAppendingPathComponent("browser.db")
var err: NSError?
NSFileManager.defaultManager().removeItemAtPath(browserDB, error: &err)
}
}
}
private class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
let browserDB = documentsPath.stringByAppendingPathComponent("browser.db")
self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB)
}
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
appDelegate.browserViewController.presentIntroViewController(force: true)
}
})
}
}
private class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
class UseCompactTabLayoutSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("CompactTabLayout") ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "CompactTabLayout")
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let clearable = EverythingClearable(profile: profile, tabmanager: tabManager)
var title: String { return NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") }
var message: String { return NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") }
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let clearString = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
alert.addAction(UIAlertAction(title: clearString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in
clearable.clear() >>== { NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataCleared, object: nil) }
}))
let cancelString = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
alert.addAction(UIAlertAction(title: cancelString, style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in }))
navigationController?.presentViewController(alert, animated: true) { () -> Void in }
}
}
private class SendCrashReportsSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("crashreports.send.always") ?? false
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "crashreports.send.always")
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
}
}
private class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
private class PopupBlockingSettings: Setting {
let prefs: Prefs
let tabManager: TabManager!
let prefKey = "blockPopups"
init(settings: SettingsTableViewController) {
self.prefs = settings.profile.prefs
self.tabManager = settings.tabManager
let title = NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")
let attributes = [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]
super.init(title: NSAttributedString(string: title, attributes: attributes))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(toggle: UISwitch) {
prefs.setObject(toggle.on, forKey: prefKey)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
var generalSettings = [
SearchSetting(settings: self),
PopupBlockingSettings(settings: self),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [UseCompactTabLayoutSetting(settings: self)]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: [
ClearPrivateDataSetting(settings: self),
SendCrashReportsSetting(settings: self),
PrivacyPolicySetting(),
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
DisconnectSetting(settings: self),
ExportBrowserDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let status = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
let section = settings[section]
if let sectionTitle = section.title?.string {
headerView.titleLabel.text = sectionTitle.uppercaseString
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0 && indexPath.row == 0) { return 64 } //make account/sign-in row taller, as per design specs
return 44
}
}
class SettingsTableFooterView: UITableViewHeaderFooterView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
var topBorder = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 0.5))
topBorder.backgroundColor = UIConstants.TableViewSeparatorColor
addSubview(topBorder)
addSubview(logo)
logo.snp_makeConstraints { (make) -> Void in
make.centerY.centerX.equalTo(self)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SettingsTableSectionHeaderView: UITableViewHeaderFooterView {
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
self.clipsToBounds = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let topBorder = CALayer()
topBorder.frame = CGRectMake(0.0, 0.0, rect.size.width, 0.5)
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(topBorder)
let bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0.0, rect.size.height - 0.5, rect.size.width, 0.5)
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(bottomBorder)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.sizeToFit()
}
}
| mpl-2.0 |
kzaher/RxSwift | RxCocoa/Foundation/NSObject+Rx.swift | 3 | 19118 | //
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import Foundation
import RxSwift
#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux)
import RxCocoaRuntime
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private var deallocatingSubjectTriggerContext: UInt8 = 0
private var deallocatingSubjectContext: UInt8 = 0
#endif
private var deallocatedSubjectTriggerContext: UInt8 = 0
private var deallocatedSubjectContext: UInt8 = 0
#if !os(Linux)
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observe<Element>(_ type: Element.Type,
_ keyPath: String,
options: KeyValueObservingOptions = [.new, .initial],
retainSelf: Bool = true) -> Observable<Element?> {
KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
/**
Observes values at the provided key path using the provided options.
- parameter keyPath: A key path between the object and one of its properties.
- parameter options: Key-value observation options, defaults to `.new` and `.initial`.
- note: When the object is deallocated, a completion event is emitted.
- returns: An observable emitting value changes at the provided key path.
*/
public func observe<Element>(_ keyPath: KeyPath<Base, Element>,
options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<Element> {
Observable<Element>.create { [weak base] observer in
let observation = base?.observe(keyPath, options: options) { obj, _ in
observer.on(.next(obj[keyPath: keyPath]))
}
return Disposables.create { observation?.invalidate() }
}
.take(until: base.rx.deallocated)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
// KVO
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observeWeakly<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable<Element?> {
return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options)
.map { n in
return n as? Element
}
}
}
#endif
// Dealloc
extension Reactive where Base: AnyObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var deallocated: Observable<Void> {
return self.synchronized {
if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable.subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable.subject
}
}
#if !DISABLE_SWIZZLING && !os(Linux)
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced before message is invoked on target object. `methodInvoked`
exists in case observing of invoked messages is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func sentMessage(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocating.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced after message is invoked on target object. `sentMessage`
exists in case interception of sent messages before they were invoked is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocated.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.methodInvoked.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var deallocating: Observable<()> {
return self.synchronized {
do {
let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
private func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: T
if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T {
subject = existingSubject
}
else {
subject = T()
objc_setAssociatedObject(
self.base,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self.base, selector, &error)
if targetImplementation == nil {
throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown
}
subject.targetImplementation = targetImplementation!
return subject
}
#endif
}
// MARK: Message interceptors
#if !DISABLE_SWIZZLING && !os(Linux)
private protocol MessageInterceptorSubject: class {
init()
var isActive: Bool {
get
}
var targetImplementation: IMP { get set }
}
private final class DeallocatingProxy
: MessageInterceptorSubject
, RXDeallocatingObserver {
typealias Element = ()
let messageSent = ReplaySubject<()>.create(bufferSize: 1)
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func deallocating() {
self.messageSent.on(.next(()))
}
deinit {
self.messageSent.on(.completed)
}
}
private final class MessageSentProxy
: MessageInterceptorSubject
, RXMessageSentObserver {
typealias Element = [AnyObject]
let messageSent = PublishSubject<[Any]>()
let methodInvoked = PublishSubject<[Any]>()
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func messageSent(withArguments arguments: [Any]) {
self.messageSent.on(.next(arguments))
}
@objc func methodInvoked(withArguments arguments: [Any]) {
self.methodInvoked.on(.next(arguments))
}
deinit {
self.messageSent.on(.completed)
self.methodInvoked.on(.completed)
}
}
#endif
private final class DeallocObservable {
let subject = ReplaySubject<Void>.create(bufferSize:1)
init() {
}
deinit {
self.subject.on(.next(()))
self.subject.on(.completed)
}
}
// MARK: KVO
#if !os(Linux)
private protocol KVOObservableProtocol {
var target: AnyObject { get }
var keyPath: String { get }
var retainTarget: Bool { get }
var options: KeyValueObservingOptions { get }
}
private final class KVOObserver
: _RXKVOObserver
, Disposable {
typealias Callback = (Any?) -> Void
var retainSelf: KVOObserver?
init(parent: KVOObservableProtocol, callback: @escaping Callback) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback)
self.retainSelf = self
}
override func dispose() {
super.dispose()
self.retainSelf = nil
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
private final class KVOObservable<Element>
: ObservableType
, KVOObservableProtocol {
typealias Element = Element?
unowned var target: AnyObject
var strongTarget: AnyObject?
var keyPath: String
var options: KeyValueObservingOptions
var retainTarget: Bool
init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) {
self.target = object
self.keyPath = keyPath
self.options = options
self.retainTarget = retainTarget
if retainTarget {
self.strongTarget = object
}
}
func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element? {
let observer = KVOObserver(parent: self) { value in
if value as? NSNull != nil {
observer.on(.next(nil))
return
}
observer.on(.next(value as? Element))
}
return Disposables.create(with: observer.dispose)
}
}
private extension KeyValueObservingOptions {
var nsOptions: NSKeyValueObservingOptions {
var result: UInt = 0
if self.contains(.new) {
result |= NSKeyValueObservingOptions.new.rawValue
}
if self.contains(.initial) {
result |= NSKeyValueObservingOptions.initial.rawValue
}
return NSKeyValueObservingOptions(rawValue: result)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable<AnyObject?> {
let components = keyPath.components(separatedBy: ".").filter { $0 != "self" }
let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options)
.finishWithNilWhenDealloc(target)
if !options.isDisjoint(with: .initial) {
return observable
}
else {
return observable
.skip(1)
}
}
// This should work correctly
// Identifiers can't contain `,`, so the only place where `,` can appear
// is as a delimiter.
// This means there is `W` as element in an array of property attributes.
private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool {
properyRuntimeInfo.range(of: ",W,") != nil
}
private extension ObservableType where Element == AnyObject? {
func finishWithNilWhenDealloc(_ target: NSObject)
-> Observable<AnyObject?> {
let deallocating = target.rx.deallocating
return deallocating
.map { _ in
return Observable.just(nil)
}
.startWith(self.asObservable())
.switchLatest()
}
}
private func observeWeaklyKeyPathFor(
_ target: NSObject,
keyPathSections: [String],
options: KeyValueObservingOptions
) -> Observable<AnyObject?> {
weak var weakTarget: AnyObject? = target
let propertyName = keyPathSections[0]
let remainingPaths = Array(keyPathSections[1..<keyPathSections.count])
let property = class_getProperty(object_getClass(target), propertyName)
if property == nil {
return Observable.error(RxCocoaError.invalidPropertyName(object: target, propertyName: propertyName))
}
let propertyAttributes = property_getAttributes(property!)
// should dealloc hook be in place if week property, or just create strong reference because it doesn't matter
let isWeak = isWeakProperty(propertyAttributes.map(String.init) ?? "")
let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.initial), retainTarget: false) as KVOObservable<AnyObject>
// KVO recursion for value changes
return propertyObservable
.flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in
if nextTarget == nil {
return Observable.just(nil)
}
let nextObject = nextTarget! as? NSObject
let strongTarget: AnyObject? = weakTarget
if nextObject == nil {
return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName))
}
// if target is alive, then send change
// if it's deallocated, don't send anything
if strongTarget == nil {
return Observable.empty()
}
let nextElementsObservable = keyPathSections.count == 1
? Observable.just(nextTarget)
: observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options)
if isWeak {
return nextElementsObservable
.finishWithNilWhenDealloc(nextObject!)
}
else {
return nextElementsObservable
}
}
}
#endif
// MARK: Constants
private let deallocSelector = NSSelectorFromString("dealloc")
// MARK: AnyObject + Reactive
extension Reactive where Base: AnyObject {
func synchronized<T>( _ action: () -> T) -> T {
objc_sync_enter(self.base)
let result = action()
objc_sync_exit(self.base)
return result
}
}
extension Reactive where Base: AnyObject {
/**
Helper to make sure that `Observable` returned from `createCachedObservable` is only created once.
This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`.
*/
func lazyInstanceObservable<T: AnyObject>(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T {
if let value = objc_getAssociatedObject(self.base, key) {
return value as! T
}
let observable = createCachedObservable()
objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observable
}
}
#endif
| mit |
fiveagency/ios-five-utils | Example/Classes/ViewControllers/ContentCell/ContentCell.swift | 1 | 5370 | //
// ContentCell.swift
// Example
//
// Created by Miran Brajsa on 21/09/16.
// Copyright © 2016 Five Agency. All rights reserved.
//
import Foundation
import UIKit
class ContentCell: UITableViewCell {
private var viewModel: ContentCellViewModel?
@IBOutlet private weak var headerView: UIView!
@IBOutlet private weak var headerMarkerView: UIView!
@IBOutlet private weak var exampleNumberLabel: UILabel!
@IBOutlet private weak var descriptionView: UIView!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var resultTitleLabel: UILabel!
@IBOutlet private weak var resultLabel: UILabel!
@IBOutlet private weak var actionButtonView: UIView!
@IBOutlet private weak var actionButton: UIButton!
@IBOutlet private weak var sliderView: UIView!
@IBOutlet private weak var slider: UISlider!
@IBOutlet private weak var firstSliderTitleLabel: UILabel!
@IBOutlet private weak var firstSliderResultTitleLabel: UILabel!
@IBOutlet private weak var secondSliderResultView: UIView!
@IBOutlet private weak var secondSliderTitleLabel: UILabel!
@IBOutlet private weak var secondSliderResultTitleLabel: UILabel!
override func awakeFromNib() {
setupAppearance()
}
func setup(withViewModel viewModel: ContentCellViewModel) {
self.viewModel = viewModel
setupContent()
setupLayout()
}
private func setupAppearance() {
guard
let headerTitleFont = UIFont.headerTitleText,
let descriptionLabelFont = UIFont.descriptionText,
let actionButtonFont = UIFont.buttonText,
let resultLabelFont = UIFont.resultLabelText,
let resultValueLabelFont = UIFont.resultValueText
else {
return
}
sliderView.backgroundColor = UIColor.white
let thumbImage = UIImage(named: "SliderDot")
slider.setThumbImage(thumbImage, for: .normal)
slider.setThumbImage(thumbImage, for: .highlighted)
slider.minimumTrackTintColor = UIColor.highlightRed
slider.maximumTrackTintColor = UIColor.headerLightGray
firstSliderTitleLabel.font = resultLabelFont
firstSliderTitleLabel.textColor = UIColor.descriptionLightGray
firstSliderResultTitleLabel.font = resultValueLabelFont
firstSliderResultTitleLabel.textColor = UIColor.descriptionDarkGray
secondSliderTitleLabel.font = resultLabelFont
secondSliderTitleLabel.textColor = UIColor.descriptionLightGray
secondSliderResultTitleLabel.font = resultValueLabelFont
secondSliderResultTitleLabel.textColor = UIColor.descriptionDarkGray
headerView.backgroundColor = UIColor.headerLightGray
headerMarkerView.backgroundColor = UIColor.headerDarkGray
exampleNumberLabel.font = headerTitleFont
exampleNumberLabel.textColor = UIColor.headerTitleGray
descriptionView.backgroundColor = UIColor.white
descriptionLabel.font = descriptionLabelFont
descriptionLabel.textColor = UIColor.descriptionDarkGray
actionButtonView.backgroundColor = UIColor.white
actionButton.titleLabel?.font = actionButtonFont
actionButton.setTitleColor(UIColor.highlightRed, for: .normal)
resultTitleLabel.font = resultLabelFont
resultTitleLabel.textColor = UIColor.descriptionLightGray
resultLabel.font = resultValueLabelFont
resultLabel.textColor = UIColor.descriptionDarkGray
}
private func setupContent() {
guard let viewModel = viewModel else { return }
exampleNumberLabel.text = viewModel.exampleTitle
descriptionLabel.text = viewModel.description
actionButton.setTitle(viewModel.actionButtonTitle, for: .normal)
resultLabel.text = viewModel.initialResult
firstSliderTitleLabel.text = viewModel.firstSliderTitle
secondSliderTitleLabel.text = viewModel.secondSliderTitle
let (firstResult, secondResult) = viewModel.initialSliderResults
firstSliderResultTitleLabel.text = firstResult
secondSliderResultTitleLabel.text = secondResult
if let sliderConfiguration = viewModel.sliderConfiguration {
slider.minimumValue = sliderConfiguration.minimumValue
slider.maximumValue = sliderConfiguration.maximumValue
slider.value = sliderConfiguration.startingValue
}
}
private func setupLayout() {
guard let viewModel = viewModel else { return }
actionButtonView.isHidden = !viewModel.shouldDisplayActionButtonView()
sliderView.isHidden = !viewModel.shouldDisplaySliderView()
secondSliderResultView.isHidden = !viewModel.shouldDisplaySecondSliderResultView()
}
@IBAction private func actionButtonTapped(_ sender: AnyObject) {
guard let viewModel = viewModel else { return }
let result = viewModel.updateButtonTapResult()
resultLabel.text = result
}
@IBAction private func sliderValueChanged(_ sender: UISlider) {
guard let viewModel = viewModel else { return }
let (firstResult, secondResult) = viewModel.updateSliderResults(newValue: sender.value)
firstSliderResultTitleLabel.text = firstResult
secondSliderResultTitleLabel.text = secondResult
}
}
| mit |
developerY/Active-Learning-Swift-2.0_DEMO | ActiveLearningSwift2.playground/Pages/Advanced.xcplaygroundpage/Contents.swift | 3 | 10329 | //: [Previous](@previous)
// ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Arithmetic operators in Swift do not automatically overflow. Adding two values that overflow
// their type (for example, storing 300 in a UInt8) will cause an error. There are special
// operators that allow overflow, including dividing by zero.
//
// * Swift allows developers to define their own operators, including those that Swift doesn't
// currently define. You can even specify the associativity and precedence for operators.
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Bitwise Operators
//
// The Bitwise operators (AND, OR, XOR, etc.) in Swift effeectively mirror the functionality that
// you're used to with C++ and Objective-C.
//
// We'll cover them briefly. The odd formatting is intended to help show the results:
var andResult: UInt8 =
0b00101111 &
0b11110100
// 0b00100100 <- result
var notResult: UInt8 =
~0b11110000
// 0b00001111 <- result
var orResult: UInt8 =
0b01010101 |
0b11110000
// 0b11110101 <- result
var xorResult: UInt8 =
0b01010101 ^
0b11110000
// 0b10100101 <- result
// Shifting in Swift is slightly different than in C++.
//
// A lesser-known fact about C++ is that the signed right-shift of a signed value is
// implementation specific. Most compilers do what most programmers expect, which is an arithmetic
// shift (which maintains the sign bit and shifts 1's into the word from the right.)
//
// Swift defines this behavior to be what you expect, shifting signed values to the right will
// perform an arithmetic shift using two's compilment.
var leftShiftUnsignedResult: UInt8 = 32 << 1
var leftShiftSignedResult: Int8 = 32 << 1
var leftShiftSignedNegativeResult: Int8 = -32 << 1
var rightShiftUnsignedResult: UInt8 = 32 >> 1
var rightShiftSignedResult: Int8 = 32 >> 1
var rightShiftSignedNegativeResult: Int8 = -32 >> 1
// ------------------------------------------------------------------------------------------------
// Overflow operators
//
// If an arithmetic operation (specifically addition (+), subtraction (-) and multiplication (*))
// results in a value too large or too small for the constant or variable that the result is
// intended for, Swift will produce an overflow/underflow error.
//
// The last two lines of this code block will trigger an overflow/underflow:
//
// var positive: Int8 = 120
// var negative: Int8 = -120
// var overflow: Int8 = positive + positive
// var underflow: Int8 = negative + negative
//
// This is also true for division by zero, which can be caused with the division (/) or remainder
// (%) operators.
//
// Sometimes, however, overflow and underflow behavior is exactly what the programmer may intend,
// so Swift provides specific overflow/underflow operators which will not trigger an error and
// allow the overflow/underflow to perform as we see in C++/Objective-C.
//
// Special operators for division by zero are also provided, which return 0 in the case of a
// division by zero.
//
// Here they are, in all their glory:
var someValue: Int8 = 120
var aZero: Int8 = someValue - someValue
var overflowAdd: Int8 = someValue &+ someValue
var underflowSub: Int8 = -someValue &- someValue
var overflowMul: Int8 = someValue &* someValue
var divByZero: Int8 = 100 &/ aZero
var remainderDivByZero: Int8 = 100 &% aZero
// ------------------------------------------------------------------------------------------------
// Operator Functions (a.k.a., Operator Overloading)
//
// Most C++ programmers should be familiar with the concept of operator overloading. Swift offers
// the same kind of functionality as well as additional functionality of specifying the operator
// precednce and associativity.
//
// The most common operators will usually take one of the following forms:
//
// * prefix: the operator appears before a single identifier as in "-a" or "++i"
// * postfix: the operator appears after a single identifier as in "i++"
// * infix: the operator appears between two identifiers as in "a + b" or "c / d"
//
// These are specified with the three attributes, @prefix, @postfix and @infix.
//
// There are more types of operators (which use different attributes, which we'll cover shortly.
//
// Let's define a Vector2D class to work with:
struct Vector2D
{
var x = 0.0
var y = 0.0
}
// Next, we'll define a simple vector addition (adding the individual x & y components to create
// a new vector.)
//
// Since we're adding two Vector2D instances, we'll use operator "+". We want our addition to take
// the form "vectorA + vectorB", which means we'll be defining an infix operator.
//
// Here's what that looks like:
func + (left: Vector2D, right: Vector2D) -> Vector2D
{
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Let's verify our work:
var a = Vector2D(x: 1.0, y: 2.0)
var b = Vector2D(x: 3.0, y: 4.0)
var c = a + b
// We've seen the infix operator at work so let's move on to the prefix and postfix operators.
// We'll define a prefix operator that negates the vector taking the form (result = -value):
prefix func - (vector: Vector2D) -> Vector2D
{
return Vector2D(x: -vector.x, y: -vector.y)
}
// Check our work:
c = -a
// Next, let's consider the common prefix increment operator (++a) and postfix increment (a++)
// operations. Each of these performs the operation on a single value whle also returning the
// appropriate result (either the original value before the increment or the value after the
// increment.)
//
// Each will either use the @prefix or @postfix attribute, but since they also modify the value
// they are also @assigmnent operators (and make use of inout for the parameter.)
//
// Let's take a look:
prefix func ++ (inout vector: Vector2D) -> Vector2D
{
vector = vector + Vector2D(x: 1.0, y: 1.0)
return vector
}
postfix func ++ (inout vector: Vector2D) -> Vector2D
{
var previous = vector;
vector = vector + Vector2D(x: 1.0, y: 1.0)
return previous
}
// And we can check our work:
++c
c++
c
// Equivalence Operators allow us to define a means for checking if two values are the same
// or equivalent. They can be "equal to" (==) or "not equal to" (!=). These are simple infix
// opertors that return a Bool result.
//
// Let's also take a moment to make sure we do this right. When comparing floating point values
// you can either check for exact bit-wise equality (a == b) or you can compare values that are
// "very close" by using an epsilon. It's important to recognize the difference, as there are
// cases when IEEE floating point values should be equal, but are actually represented differently
// in their bit-wise format because they were calculated differently. In these cases, a simple
// equality comparison will not suffice.
//
// So here are our more robust equivalence operators:
let Epsilon = 0.1e-7
func == (left: Vector2D, right: Vector2D) -> Bool
{
if abs(left.x - right.x) > Epsilon { return false }
if abs(left.y - right.y) > Epsilon { return false }
return true
}
func != (left: Vector2D, right: Vector2D) -> Bool
{
// Here, we'll use the inverted result of the "==" operator:
return !(left == right)
}
// ------------------------------------------------------------------------------------------------
// Custom Operators
//
// So far, we've been defining operator functions for operators that Swift understands and
// for which Swift provides defined behaviors. We can also define our own custom operators for
// doing other interestig things.
//
// For example, Swift doesn't support the concept of a "vector normalization" or "cross product"
// because this functionality doesn't apply to any of the types Swift offers.
//
// Let's keep it simple, though. How about an operator that adds a vector to itself. Let's make
// this a prefix operator that takes the form "+++value"
//
// First, we we must introduce Swift to our new operator. The syntax takes the form of the
// 'operator' keyword, folowed by either 'prefix', 'postfix' or 'infix':
//
// Swift meet operator, operator meet swift:
prefix operator +++ {}
// Now we can declare our new operator:
prefix func +++ (inout vector: Vector2D) -> Vector2D
{
vector = vector + vector
return vector
}
// Let's check our work:
var someVector = Vector2D(x: 5.0, y: 9.0)
+++someVector
// ------------------------------------------------------------------------------------------------
// Precedence and Associativity for Custom Infix Operators
//
// Custom infix operators can define their own associativity (left-to-right or right-to-left or
// none) as well as a precedence for determining the order of operations.
//
// Associativity values are 'left' or 'right' or 'none'.
//
// Precedence values are ranked with a numeric value. If not specified, the default value is 100.
// Operations are performed in order of precedence, with higher values being performed first. The
// precedence values are relative to all other precedence values for other operators. The following
// are the default values for operator precedence in the Swift standard library:
//
// 160 (none): Operators << >>
// 150 (left): Operators * / % &* &/ &% &
// 140 (left): Operators + - &+ &- | ^
// 135 (none): Operators .. ...
// 132 (none): Operators is as
// 130 (none): Operators < <= > >= == != === !== ~=
// 120 (left): Operators &&
// 110 (left): Operators ||
// 100 (right): Operators ?:
// 90 (right): Operators = *= /= %= += -= <<= >>= &= ^= |= &&= ||=
//
// Let's take a look at how we define a new custom infix operator with left associativity and a
// precedence of 140.
//
// We'll define a function that adds the 'x' components of two vectors, but subtracts the 'y'
// components. We'll call this the "+-" operator:
infix operator +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> Vector2D
{
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
// Check our work. Let's setup a couple vectors that result in a value of (0, 0):
var first = Vector2D(x: 5.0, y: 5.0)
var second = Vector2D(x: -5.0, y: 5.0)
first +- second
//: [Next](@next)
| apache-2.0 |
zitao0322/ShopCar | Shoping_Car/Shoping_Car/Extension/Communal.swift | 1 | 1769 |
import Foundation
import UIKit
//MARK:颜色公共的方法
//随机颜色
func kStochasticColor() -> UIColor{
return kColorDefine(r: CGFloat(random()%255),
g: CGFloat(random()%255),
b: CGFloat(random()%255))
}
//自定义颜色
func kColorDefine(r r: CGFloat,g: CGFloat,b: CGFloat) -> UIColor {
return UIColor(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
//MARK:字体
let kFont_11 = UIFont.systemFontOfSize(11)
let kFont_12 = UIFont.systemFontOfSize(12)
let kFont_14 = UIFont.systemFontOfSize(14)
let kFont_15 = UIFont.systemFontOfSize(15)
let kFont_18 = UIFont.systemFontOfSize(18)
let kFont_19 = UIFont.systemFontOfSize(19)
//MARK:长宽
//定义宏
let kSCREENW = UIScreen.mainScreen().bounds.width
let kSCREENH = UIScreen.mainScreen().bounds.height
/**
根据比例计算横向的UI尺寸
- parameter w: UI标注的尺寸
- returns: 换算过后尺寸
*/
func kAUTO_WEX(w: CGFloat) -> CGFloat {
return w*kSCREEN_WIDTH_RATIO
}
/**
根据比例计算纵向的UI尺寸
- parameter h: UI标注的尺寸
- returns: 换算过后尺寸
*/
func kAUTO_HEX(h: CGFloat) -> CGFloat {
return h*kSCREEN_HEIGHT_RATIO
}
//计算现在屏幕和苹果6屏幕的比例
private let kSCREEN_WIDTH_RATIO: CGFloat = kSCREENW/375.0
private let kSCREEN_HEIGHT_RATIO: CGFloat = kSCREENH/667.0
func println<T>(message: T,
fileName: String = #file,
methodName: String = #function,
lineNumber: Int = #line)
{
#if DEBUG
let str: String = (fileName as NSString)
.pathComponents.last!
.stringByReplacingOccurrencesOfString("swift", withString: "")
print("\(str)\(methodName)[\(lineNumber)]:\(message)")
#endif
}
| mit |
realm/SwiftLint | Source/SwiftLintFramework/Reporters/JSONReporter.swift | 1 | 1029 | import Foundation
import SourceKittenFramework
/// Reports violations as a JSON array.
public struct JSONReporter: Reporter {
// MARK: - Reporter Conformance
public static let identifier = "json"
public static let isRealtime = false
public var description: String {
return "Reports violations as a JSON array."
}
public static func generateReport(_ violations: [StyleViolation]) -> String {
return toJSON(violations.map(dictionary(for:)))
}
// MARK: - Private
private static func dictionary(for violation: StyleViolation) -> [String: Any] {
return [
"file": violation.location.file ?? NSNull() as Any,
"line": violation.location.line ?? NSNull() as Any,
"character": violation.location.character ?? NSNull() as Any,
"severity": violation.severity.rawValue.capitalized,
"type": violation.ruleName,
"rule_id": violation.ruleIdentifier,
"reason": violation.reason
]
}
}
| mit |
The-iPocalypse/BA-iOS-Application | src/Constants.swift | 1 | 285 | //
// Constants.swift
// BA-iOS-Application
//
// Created by Vincent Dupuis on 2016-02-12.
// Copyright © 2016 Samuel Bellerose. All rights reserved.
//
import Foundation
public struct Constants {
struct api {
static let baseURL = "http://159.203.27.0:8080/"
}
} | mit |
aman19ish/CommonCodeSwift | CommonCodeSwift/Extensions/UITextView/UITextViewClassExtension/UITextViewClassExtension.swift | 1 | 862 | //
// UITextViewClassExtension.swift
// CommonCodeSwift
//
// Created by Aman Gupta on 13/06/17.
// Copyright © 2017 aman19ish. All rights reserved.
//
import UIKit
@IBDesignable
class UITextViewClassExtension: UItextViewBorder {
/**
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func layoutSubviews() {
super.layoutSubviews()
setup()
font = FontType.getFont(rawValue: fontTypeInterger, fontSize: fontSize)
}
func setup() {
self.textContainerInset = UIEdgeInsets.init(top: self.borderWidth, left: 0 , bottom: self.borderWidth, right: 0);
self.textContainer.lineFragmentPadding = self.borderWidth;
}
}
| mit |
dreamsxin/swift | test/Interpreter/capture_top_level.swift | 9 | 1030 | // RUN: %target-run-simple-swift | FileCheck %s
// RUN: %target-build-swift -DVAR %s -o %t-var
// RUN: %target-run %t-var | FileCheck %s
// RUN: %target-build-swift -DVAR_UPDATE %s -o %t-var
// RUN: %target-run %t-var | FileCheck %s
// REQUIRES: executable_test
#if VAR_UPDATE
guard var x = Optional(0) else { fatalError() }
#elseif VAR
guard var x = Optional(42) else { fatalError() }
#else
guard let x = Optional(42) else { fatalError() }
#endif
_ = 0 // intervening code
func function() {
print("function: \(x)")
}
let closure: () -> Void = {
print("closure: \(x)")
}
defer {
print("deferred: \(x)")
}
#if VAR_UPDATE
x = 42
#endif
let closureCapture: () -> Void = { [x] in
// Must come after the assignment because of the capture by value.
print("closure-capture: \(x)")
}
print("go! \(x)") // CHECK-LABEL: go! 42
function() // CHECK-NEXT: function: 42
closure() // CHECK-NEXT: closure: 42
closureCapture() // CHECK-NEXT: closure-capture: 42
print("done?") // CHECK-NEXT: done?
// CHECK-NEXT: deferred: 42
| apache-2.0 |
sjrmanning/Birdsong | Source/Response.swift | 1 | 965 | //
// Response.swift
// Pods
//
// Created by Simon Manning on 23/06/2016.
//
//
import Foundation
open class Response {
open let ref: String
open let topic: String
open let event: String
open let payload: Socket.Payload
init?(data: Data) {
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? Socket.Payload else { return nil }
ref = jsonObject["ref"] as? String ?? ""
if let topic = jsonObject["topic"] as? String,
let event = jsonObject["event"] as? String,
let payload = jsonObject["payload"] as? Socket.Payload {
self.topic = topic
self.event = event
self.payload = payload
}
else {
return nil
}
}
catch {
return nil
}
}
}
| mit |
yoller/HanekeSwift | Haneke/Cache.swift | 1 | 13738 | //
// Cache.swift
// Haneke
//
// Created by Luis Ascorbe on 23/07/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
// Used to add T to NSCache
class ObjectWrapper : NSObject {
let value: Any
init(value: Any) {
self.value = value
}
}
extension HanekeGlobals {
// It'd be better to define this in the Cache class but Swift doesn't allow statics in a generic type
public struct Cache {
public static let OriginalFormatName = "original"
public enum ErrorCode : Int {
case ObjectNotFound = -100
case FormatNotFound = -101
}
}
}
public class Cache<T: DataConvertible where T.Result == T, T : DataRepresentable> {
let name: String
var memoryWarningObserver : NSObjectProtocol!
public init(name: String) {
self.name = name
let notifications = NSNotificationCenter.defaultCenter()
// Using block-based observer to avoid subclassing NSObject
memoryWarningObserver = notifications.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification,
object: nil,
queue: NSOperationQueue.mainQueue(),
usingBlock: { [unowned self] (notification : NSNotification!) -> Void in
self.onMemoryWarning()
}
)
let originalFormat = Format<T>(name: HanekeGlobals.Cache.OriginalFormatName)
self.addFormat(originalFormat)
}
deinit {
let notifications = NSNotificationCenter.defaultCenter()
notifications.removeObserver(memoryWarningObserver, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
public func set(value value: T, key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: ((T) -> ())? = nil) {
if let (format, memoryCache, diskCache) = self.formats[formatName] {
self.format(value: value, format: format) { formattedValue in
let wrapper = ObjectWrapper(value: formattedValue)
memoryCache.setObject(wrapper, forKey: key)
// Value data is sent as @autoclosure to be executed in the disk cache queue.
diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key)
succeed?(formattedValue)
}
} else {
assertionFailure("Can't set value before adding format")
}
}
public func fetch(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Cache.buildFetch(failure: fail, success: succeed)
if let (format, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper, let result = wrapper.value as? T {
fetch.succeed(result)
diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key)
return fetch
}
self.fetchFromDiskCache(diskCache, key: key, memoryCache: memoryCache, failure: { error in
fetch.fail(error)
}) { value in
fetch.succeed(value)
}
} else {
let localizedFormat = NSLocalizedString("Format %@ not found", comment: "Error description")
let description = String(format:localizedFormat, formatName)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue, description: description)
fetch.fail(error)
}
return fetch
}
public func fetchFromMemory(key key : String, formatName : String = HanekeGlobals.Cache.OriginalFormatName) -> T? {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper {
return wrapper.value as? T
}
let path = diskCache.pathForKey(key)
do {
let data = try NSData(contentsOfFile: path, options: NSDataReadingOptions())
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
return wrapper.value as? T
}
diskCache.updateDiskAccessDateAtPath(path)
} catch {
}
} else {
return nil
}
return nil
}
public func fetch(fetcher fetcher : Fetcher<T>, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let key = fetcher.key
let fetch = Cache.buildFetch(failure: fail, success: succeed)
self.fetch(key: key, formatName: formatName, failure: { error in
if error?.code == HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue {
fetch.fail(error)
}
if let (format, _, _) = self.formats[formatName] {
self.fetchAndSet(fetcher, format: format, failure: {error in
fetch.fail(error)
}) {value in
fetch.succeed(value)
}
}
// Unreachable code. Formats can't be removed from Cache.
}) { value in
fetch.succeed(value)
}
return fetch
}
public func remove(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
memoryCache.removeObjectForKey(key)
diskCache.removeData(key)
}
}
public func removeAll(completion: (() -> ())? = nil) {
let group = dispatch_group_create();
for (_, (_, memoryCache, diskCache)) in self.formats {
memoryCache.removeAllObjects()
dispatch_group_enter(group)
diskCache.removeAllData {
dispatch_group_leave(group)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC))
if dispatch_group_wait(group, timeout) != 0 {
Log.error("removeAll timed out waiting for disk caches")
}
let path = self.cachePath
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {
Log.error("Failed to remove path \(path)", error as NSError)
}
if let completion = completion {
dispatch_async(dispatch_get_main_queue()) {
completion()
}
}
}
}
// MARK: Size
public var size: UInt64 {
var size: UInt64 = 0
for (_, (_, _, diskCache)) in self.formats {
dispatch_sync(diskCache.cacheQueue) { size += diskCache.size }
}
return size
}
// MARK: Notifications
func onMemoryWarning() {
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
}
// MARK: Formats
var formats : [String : (Format<T>, NSCache, DiskCache)] = [:]
public func addFormat(format : Format<T>) {
let name = format.name
let formatPath = self.formatPath(formatName: name)
let memoryCache = NSCache()
let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity)
self.formats[name] = (format, memoryCache, diskCache)
}
// MARK: Internal
lazy var cachePath: String = {
let basePath = DiskCache.basePath()
let cachePath = (basePath as NSString).stringByAppendingPathComponent(self.name)
return cachePath
}()
func formatPath(formatName formatName: String) -> String {
let formatPath = (self.cachePath as NSString).stringByAppendingPathComponent(formatName)
do {
try NSFileManager.defaultManager().createDirectoryAtPath(formatPath, withIntermediateDirectories: true, attributes: nil)
} catch {
Log.error("Failed to create directory \(formatPath)", error as NSError)
}
return formatPath
}
// MARK: Private
func dataFromValue(value : T, format : Format<T>) -> NSData? {
if let data = format.convertToData?(value) {
return data
}
return value.asData()
}
private func fetchFromDiskCache(diskCache : DiskCache, key: String, memoryCache : NSCache, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
diskCache.fetchData(key: key, failure: { error in
if let block = fail {
if (error?.code == NSFileReadNoSuchFileError) {
let localizedFormat = NSLocalizedString("Object not found for key %@", comment: "Error description")
let description = String(format:localizedFormat, key)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.ObjectNotFound.rawValue, description: description)
block(error)
} else {
block(error)
}
}
}) { data in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
dispatch_async(dispatch_get_main_queue(), {
succeed(descompressedValue)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
})
}
})
}
}
private func fetchAndSet(fetcher : Fetcher<T>, format : Format<T>, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
fetcher.fetch(failure: { error in
let _ = fail?(error)
}) { value in
self.set(value: value, key: fetcher.key, formatName: format.name, success: succeed)
}
}
private func format(value value : T, format : Format<T>, success succeed : (T) -> ()) {
// HACK: Ideally Cache shouldn't treat images differently but I can't think of any other way of doing this that doesn't complicate the API for other types.
if format.isIdentity && !(value is UIImage) {
succeed(value)
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var formatted = format.apply(value)
if let formattedImage = formatted as? UIImage {
let originalImage = value as? UIImage
if formattedImage === originalImage {
formatted = self.decompressedImageIfNeeded(formatted)
}
}
dispatch_async(dispatch_get_main_queue()) {
succeed(formatted)
}
}
}
}
private func decompressedImageIfNeeded(value : T) -> T {
if let image = value as? UIImage {
let decompressedImage = image.hnk_decompressedImage() as? T
return decompressedImage!
}
return value
}
private class func buildFetch(failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Fetch<T>()
if let succeed = succeed {
fetch.onSuccess(succeed)
}
if let fail = fail {
fetch.onFailure(fail)
}
return fetch
}
// MARK: Convenience fetch
// Ideally we would put each of these in the respective fetcher file as a Cache extension. Unfortunately, this fails to link when using the framework in a project as of Xcode 6.1.
public func fetch(key key: String, @autoclosure(escaping) value getValue : () -> T.Result, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = SimpleFetcher<T>(key: key, value: getValue)
return self.fetch(fetcher: fetcher, formatName: formatName, success: succeed)
}
public func fetch(path path: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = DiskFetcher<T>(path: path)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
public func fetch(URL URL : NSURL, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = NetworkFetcher<T>(URL: URL)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
}
| apache-2.0 |
digdoritos/RestfulAPI-Example | RestfulAPI-Example/FavoritesViewController.swift | 1 | 893 | //
// FavoritesViewController.swift
// RestfulAPI-Example
//
// Created by Chun-Tang Wang on 26/03/2017.
// Copyright © 2017 Chun-Tang Wang. All rights reserved.
//
import UIKit
class FavoritesViewController: UIViewController {
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.
}
/*
// 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 |
slavapestov/swift | test/Interpreter/protocol_extensions.swift | 3 | 5890 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Extend a protocol with a property.
extension SequenceType {
final var myCount: Int {
var result = 0
for _ in self {
result += 1
}
return result
}
}
// CHECK: 4
print(["a", "b", "c", "d"].myCount)
// Extend a protocol with a function.
extension CollectionType {
final var myIndices: Range<Index> {
return Range(start: startIndex, end: endIndex)
}
func clone() -> Self {
return self
}
}
// CHECK: 4
print(["a", "b", "c", "d"].clone().myCount)
extension CollectionType {
final func indexMatching(fn: Generator.Element -> Bool) -> Index? {
for i in myIndices {
if fn(self[i]) { return i }
}
return nil
}
}
// CHECK: 2
print(["a", "b", "c", "d"].indexMatching({$0 == "c"})!)
// Extend certain instances of a collection (those that have equatable
// element types) with another algorithm.
extension CollectionType where Self.Generator.Element : Equatable {
final func myIndexOf(element: Generator.Element) -> Index? {
for i in self.indices {
if self[i] == element { return i }
}
return nil
}
}
// CHECK: 3
print(["a", "b", "c", "d", "e"].myIndexOf("d")!)
extension SequenceType {
final public func myEnumerate() -> EnumerateSequence<Self> {
return EnumerateSequence(self)
}
}
// CHECK: (0, a)
// CHECK-NEXT: (1, b)
// CHECK-NEXT: (2, c)
for (index, element) in ["a", "b", "c"].myEnumerate() {
print("(\(index), \(element))")
}
extension SequenceType {
final public func myReduce<T>(
initial: T, @noescape combine: (T, Self.Generator.Element) -> T
) -> T {
var result = initial
for value in self {
result = combine(result, value)
}
return result
}
}
// CHECK: 15
print([1, 2, 3, 4, 5].myReduce(0, combine: +))
extension SequenceType {
final public func myZip<S : SequenceType>(s: S) -> Zip2Sequence<Self, S> {
return Zip2Sequence(self, s)
}
}
// CHECK: (1, a)
// CHECK-NEXT: (2, b)
// CHECK-NEXT: (3, c)
for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) {
print("(\(a), \(b))")
}
// Mutating algorithms.
extension MutableCollectionType
where Self.Index: RandomAccessIndexType, Self.Generator.Element : Comparable {
public final mutating func myPartition(range: Range<Index>) -> Index {
return self.partition(range)
}
}
// CHECK: 4 3 1 2 | 5 9 8 6 7 6
var evenOdd = [5, 3, 6, 2, 4, 9, 8, 1, 7, 6]
var evenOddSplit = evenOdd.myPartition(evenOdd.myIndices)
for i in evenOdd.myIndices {
if i == evenOddSplit { print(" |", terminator: "") }
if i > 0 { print(" ", terminator: "") }
print(evenOdd[i], terminator: "")
}
print("")
extension RangeReplaceableCollectionType {
public final func myJoin<S : SequenceType where S.Generator.Element == Self>(
elements: S
) -> Self {
var result = Self()
var gen = elements.generate()
if let first = gen.next() {
result.appendContentsOf(first)
while let next = gen.next() {
result.appendContentsOf(self)
result.appendContentsOf(next)
}
}
return result
}
}
// CHECK: a,b,c
print(
String(
",".characters.myJoin(["a".characters, "b".characters, "c".characters])
)
)
// Constrained extensions for specific types.
extension CollectionType where Self.Generator.Element == String {
final var myCommaSeparatedList: String {
if startIndex == endIndex { return "" }
var result = ""
var first = true
for x in self {
if first { first = false }
else { result += ", " }
result += x
}
return result
}
}
// CHECK: x, y, z
print(["x", "y", "z"].myCommaSeparatedList)
// CHECK: {{[tuv], [tuv], [tuv]}}
print((["t", "u", "v"] as Set).myCommaSeparatedList)
// Existentials
protocol ExistP1 {
func existP1()
}
extension ExistP1 {
final func runExistP1() {
print("runExistP1")
self.existP1()
}
}
struct ExistP1_Struct : ExistP1 {
func existP1() {
print(" - ExistP1_Struct")
}
}
class ExistP1_Class : ExistP1 {
func existP1() {
print(" - ExistP1_Class")
}
}
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Struct
var existP1: ExistP1 = ExistP1_Struct()
existP1.runExistP1()
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Class
existP1 = ExistP1_Class()
existP1.runExistP1()
protocol P {
mutating func setValue(b: Bool)
func getValue() -> Bool
}
extension P {
final var extValue: Bool {
get { return getValue() }
set(newValue) { setValue(newValue) }
}
}
extension Bool : P {
mutating func setValue(b: Bool) { self = b }
func getValue() -> Bool { return self }
}
class C : P {
var theValue: Bool = false
func setValue(b: Bool) { theValue = b }
func getValue() -> Bool { return theValue }
}
func toggle(inout value: Bool) {
value = !value
}
var p: P = true
// CHECK: Bool
print("Bool")
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// CHECK: C
print("C")
p = C()
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// Logical lvalues of existential type.
struct HasP {
var _p: P
var p: P {
get { return _p }
set { _p = newValue }
}
}
var hasP = HasP(_p: false)
// CHECK: true
hasP.p.extValue = true
print(hasP.p.extValue)
// CHECK: false
toggle(&hasP.p.extValue)
print(hasP.p.extValue)
// rdar://problem/20739719
class Super: Init {
required init(x: Int) { print("\(x) \(self.dynamicType)") }
}
class Sub: Super {}
protocol Init { init(x: Int) }
extension Init { init() { self.init(x: 17) } }
// CHECK: 17 Super
_ = Super()
// CHECK: 17 Sub
_ = Sub()
// CHECK: 17 Super
var sup: Super.Type = Super.self
_ = sup.init()
// CHECK: 17 Sub
sup = Sub.self
_ = sup.init()
// CHECK: DONE
print("DONE")
| apache-2.0 |
seanmcneil/CodeHunter | CodeHunter/Classes/Extensions/AVCaptureSession+Extension.swift | 1 | 368 | //
// AVCaptureSession+Extension.swift
// Pods
//
// Created by seanmcneil on 5/22/17.
//
//
import AVFoundation
extension AVCaptureSession {
var isAuthorized: Bool {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized, .notDetermined:
return true
default:
return false
}
}
}
| mit |
luizilha/Alert-Coin | Alert Coin/MainCell.swift | 1 | 313 | //
// MainCell.swift
// Alert Coin
//
// Created by Luiz Ilha on 7/29/15.
// Copyright (c) 2015 Ilha. All rights reserved.
//
import UIKit
class MainCell: UITableViewCell {
@IBOutlet weak var coinName: UILabel!
@IBOutlet weak var coinValue: UILabel!
@IBOutlet weak var variation: UILabel!
} | mit |
ipraba/EPSignature | Example/Tests/Tests.swift | 1 | 846 | //
// ViewController.swift
// EPSignature
//
// Created by Prabaharan on 01/13/2016.
// Modified By C0mrade on 27/09/2016.
// Copyright (c) 2016 Prabaharan. All rights reserved.
//
import XCTest
import EPSignature
class EPCalendarTests: 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 test1 () {
let signatureView = EPSignatureView(frame: CGRect(x: 0, y: 0, width: 240, height: 320))
XCTAssertNil(signatureView.getSignatureAsImage())
XCTAssertFalse(signatureView.isSigned)
}
}
| mit |
kentaiwami/masamon | masamon/masamon/Setting.swift | 1 | 3684 | //
// Setting.swift
// masamon
//
// Created by 岩見建汰 on 2016/01/31.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
import Eureka
class Setting: FormViewController {
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate //AppDelegateのインスタンスを取得
override func viewDidLoad() {
super.viewDidLoad()
//ナビゲーションバーの色などを設定する
self.navigationController!.navigationBar.barTintColor = UIColor.black
self.navigationController!.navigationBar.tintColor = UIColor.white
self.navigationController!.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
let storyboard: UIStoryboard = self.storyboard!
let HourlyWageSetting_VC = storyboard.instantiateViewController(withIdentifier: "HourlyWageSetting")
let ShiftImportSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftImportSetting")
let StaffNameListSetting_VC = storyboard.instantiateViewController(withIdentifier: "StaffNameListSetting")
let ShiftNameListSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftNameListSetting")
let ShiftListSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftListSetting")
form +++ Section()
<<< ButtonRow() {
$0.title = "時給の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return HourlyWageSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "ユーザ名と従業員数の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftImportSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "従業員名の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return StaffNameListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "シフト名の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftNameListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "取り込んだシフトの設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
}
override func viewDidAppear(_ animated: Bool) {
appDelegate.screennumber = 2
}
}
| mit |
suifengqjn/CatLive | CatLive/CatLive/Classes/Home/Controllers/AnchorController.swift | 1 | 2866 | //
// AnchorController.swift
// CatLive
//
// Created by qianjn on 2017/6/11.
// Copyright © 2017年 SF. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 8
private let kAnchorCellID = "kAnchorCellID"
class AnchorController: XCViewController {
// MARK: 对外属性
var homeType : HomeType!
// MARK: 定义属性
fileprivate lazy var homeVM : HomeViewModel = HomeViewModel()
lazy var collectionView: UICollectionView = {
let layout = CLWaterFallLayout()
layout.dataSource = self
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "HomeViewCell", bundle: nil), forCellWithReuseIdentifier: kAnchorCellID)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData(index: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collectionView.reloadData()
}
}
// MARK:- 设置UI界面内容
extension AnchorController {
fileprivate func setupUI() {
view.addSubview(collectionView)
}
}
extension AnchorController {
fileprivate func loadData(index : Int) {
homeVM.loadHomeData(type: homeType, index : index, finishedCallback: {
self.collectionView.reloadData()
})
}
}
// MARK:- collectionView的数据源&代理
extension AnchorController: UICollectionViewDataSource, UICollectionViewDelegate, CLWaterFallLayoutDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return homeVM.anchorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAnchorCellID, for: indexPath) as! HomeViewCell
cell.anchorModel = homeVM.anchorModels[indexPath.item]
if indexPath.item == homeVM.anchorModels.count - 1 {
loadData(index: homeVM.anchorModels.count)
}
return cell
}
func waterfallLayout(_ layout: CLWaterFallLayout, indexPath: IndexPath) -> CGFloat {
return indexPath.item % 2 == 0 ? kScreenW * 2 / 3 : kScreenW * 0.5
}
}
| apache-2.0 |
ahoppen/swift | test/SILGen/protocols.swift | 17 | 22622 |
// RUN: %target-swift-emit-silgen -module-name protocols %s | %FileCheck %s
//===----------------------------------------------------------------------===//
// Calling Existential Subscripts
//===----------------------------------------------------------------------===//
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
func use_subscript_rvalue_get(_ i : Int) -> Int {
return subscriptableGet[i]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_rvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack
// CHECK-NEXT: copy_addr [[ALLOCSTACK]] to [initialization] [[TMP]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[TMP]])
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_get(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_set(_ i : Int) {
subscriptableGetSet[i] = i
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Subscripts
//===----------------------------------------------------------------------===//
func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_rvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter
// CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_subscript_archetype_rvalue_get
func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter
// CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]])
// CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T
// CHECK: return [[APPLYRESULT]]
func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) {
generic[idx] = idx
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter
// CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Existential Properties
//===----------------------------------------------------------------------===//
protocol PropertyWithGetter {
var a : Int { get }
}
protocol PropertyWithGetterSetter {
var b : Int { get set }
}
var propertyGet : PropertyWithGetter
var propertyGetSet : PropertyWithGetterSetter
func use_property_rvalue_get() -> Int {
return propertyGet.a
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_rvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter
// CHECK: [[BORROW:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[COPY]] to [initialization] [[BORROW]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[BORROW]])
func use_property_lvalue_get() -> Int {
return propertyGetSet.b
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]])
func use_property_lvalue_set(_ x : Int) {
propertyGetSet.b = x
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Properties
//===----------------------------------------------------------------------===//
func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int {
return generic.a
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_rvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]]
// CHECK-NEXT: dealloc_stack [[STACK]]
// CHECK: } // end sil function '{{.*}}use_property_archetype_rvalue_get
func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int {
return generic.b
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_property_archetype_lvalue_get
func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) {
generic.b = v
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter
// CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Initializers
//===----------------------------------------------------------------------===//
protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F
func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) {
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[T_RESULT]] : $*T
// CHECK: dealloc_stack [[T_RESULT]] : $*T
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
T(int: i)
}
// CHECK: sil hidden [ossa] @$s9protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F
func use_initializable_existential(_ im: Initializable.Type, i: Int) {
// CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int):
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable
// CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable
im.init(int: i)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
//===----------------------------------------------------------------------===//
// Protocol conformance and witness table generation
//===----------------------------------------------------------------------===//
class ClassWithGetter : PropertyWithGetter {
var a: Int {
get {
return 42
}
}
}
// Make sure we are generating a protocol witness that calls the class method on
// ClassWithGetter.
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*ClassWithGetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter {
var a: Int {
get {
return 1
}
set {}
}
var b: Int {
get {
return 2
}
set {}
}
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW :
// CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
// Stored variables fulfilling property requirements
//
class ClassWithStoredProperty : PropertyWithGetter {
var a : Int = 0
// Make sure that accesses go through the generated accessors for classes.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols23ClassWithStoredPropertyC011methodUsingE0SiyF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty):
// CHECK-NEXT: debug_value [[ARG]]
// CHECK-NOT: copy_value
// CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]])
// CHECK-NOT: destroy_value
// CHECK-NEXT: return [[RESULT]] : $Int
}
struct StructWithStoredProperty : PropertyWithGetter {
var a : Int
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols24StructWithStoredPropertyV011methodUsingE0SiyF
// CHECK: bb0(%0 : $StructWithStoredProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a
// CHECK-NEXT: return %2 : $Int
}
// Make sure that we generate direct function calls for out struct protocol
// witness since structs don't do virtual calls for methods.
//
// *NOTE* Even though at first glance the copy_addr looks like a leak
// here, StructWithStoredProperty is a trivial struct implying that no
// leak is occurring. See the test with StructWithStoredClassProperty
// that makes sure in such a case we don't leak. This is due to the
// thunking code being too dumb but it is harmless to program
// correctness.
//
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: return
class C {}
// Make sure that if the getter has a class property, we pass it in
// in_guaranteed and don't leak.
struct StructWithStoredClassProperty : PropertyWithGetter {
var a : Int
var c: C = C()
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF
// CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a
// CHECK-NEXT: return %2 : $Int
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
// rdar://22676810
protocol ExistentialProperty {
var p: PropertyWithGetterSetter { get set }
}
func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) {
let b = t.p.b
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter
// CHECK: [[T_TEMP:%.*]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T
// CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter :
// CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]])
// CHECK-NEXT: destroy_addr [[T_TEMP]]
// CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]]
// CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]]
// CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]])
// CHECK-NEXT: debug_value
// CHECK-NEXT: destroy_addr [[T0]]
// CHECK-NOT: witness_method
// CHECK: return
func modify(_ x: inout Int) {}
func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
modify(&x.b)
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!modify
// CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[WITNESS_FN]]<T>
// CHECK: [[MODIFY_FN:%.*]] = function_ref @$s9protocols6modifyyySizF
// CHECK: apply [[MODIFY_FN]]([[ADDR]])
// CHECK: end_apply [[TOKEN]]
public struct Val {
public var x: Int = 0
}
public protocol Proto {
var val: Val { get nonmutating set}
}
public func test(_ p: Proto) {
p.val.x += 1
}
// CHECK-LABEL: sil [ossa] @$s9protocols4testyyAA5Proto_pF : $@convention(thin) (@in_guaranteed Proto) -> ()
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
// CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}") Proto, #Proto.val!modify
// CHECK: ([[BUF:%.*]], [[TOKEN:%.*]]) = begin_apply [[MAT]]
// CHECK: end_apply [[TOKEN]]
// CHECK: return
// SR-11748
protocol SelfReturningSubscript {
subscript(b: Int) -> Self { get }
}
public func testSelfReturningSubscript() {
// CHECK-LABEL: sil private [ossa] @$s9protocols26testSelfReturningSubscriptyyFAA0cdE0_pAaC_pXEfU_
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
// CHECK: [[OPEN_ADDR:%.*]] = alloc_stack $@opened("{{.*}}") SelfReturningSubscript
// CHECK: copy_addr [[OPEN]] to [initialization] [[OPEN_ADDR]] : $*@opened("{{.*}}") SelfReturningSubscript
// CHECK: [[WIT_M:%.*]] = witness_method $@opened("{{.*}}") SelfReturningSubscript, #SelfReturningSubscript.subscript!getter
// CHECK: apply [[WIT_M]]<@opened("{{.*}}") SelfReturningSubscript>({{%.*}}, {{%.*}}, [[OPEN_ADDR]])
_ = [String: SelfReturningSubscript]().mapValues { $0[2] }
}
// CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols {
// CHECK-NEXT: method #PropertyWithGetterSetter.b!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!setter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!modify: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivMTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
| apache-2.0 |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSPhotoViewController.swift | 1 | 7754 | //
// INSPhotoViewController.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import AVKit
open class INSPhotoViewController: UIViewController, UIScrollViewDelegate {
var photo: INSPhotoViewable
var longPressGestureHandler: ((UILongPressGestureRecognizer) -> ())?
lazy private(set) var scalingImageView: INSScalingImageView = {
return INSScalingImageView()
}()
lazy private(set) var doubleTapGestureRecognizer: UITapGestureRecognizer = {
let gesture = UITapGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleDoubleTapWithGestureRecognizer(_:)))
gesture.numberOfTapsRequired = 2
return gesture
}()
lazy private(set) var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleLongPressWithGestureRecognizer(_:)))
return gesture
}()
lazy private(set) var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.startAnimating()
return activityIndicator
}()
public init(photo: INSPhotoViewable) {
self.photo = photo
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
scalingImageView.delegate = nil
}
let playerController = INSVideoPlayerViewController()
open override func viewDidLoad() {
super.viewDidLoad()
scalingImageView.delegate = self
scalingImageView.frame = view.bounds
scalingImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(scalingImageView)
view.addSubview(activityIndicator)
activityIndicator.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
activityIndicator.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin]
activityIndicator.sizeToFit()
if photo.localVideoURL != nil || photo.videoURL != nil {
playerController.view.addSubview(scalingImageView)
playerController.view.frame = view.bounds
if let urlString = photo.localVideoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
} else if let urlString = photo.videoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
}
playerController.view.addGestureRecognizer(doubleTapGestureRecognizer)
}
else {
view.addGestureRecognizer(doubleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
}
if let image = photo.image {
self.scalingImageView.image = image
self.activityIndicator.stopAnimating()
} else if let thumbnailImage = photo.thumbnailImage {
self.scalingImageView.image = blurEffect(image: thumbnailImage)
loadFullSizeImage()
} else {
loadThumbnailImage()
}
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scalingImageView.frame = view.bounds
playerController.view.frame = view.bounds
}
private func loadThumbnailImage() {
view.bringSubviewToFront(activityIndicator)
photo.loadThumbnailImageWithCompletionHandler { [weak self] (image, error) -> () in
let completeLoading = {
self?.scalingImageView.image = blurEffect(image: image ?? UIImage())
// if image != nil {
// // self?.activityIndicator.stopAnimating()
// }
self?.loadFullSizeImage()
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
}
}
private func loadFullSizeImage() {
print("loading full size")
view.bringSubviewToFront(activityIndicator)
self.photo.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in
let completeLoading = {
self?.activityIndicator.stopAnimating()
self?.scalingImageView.image = image
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
})
}
@objc private func handleLongPressWithGestureRecognizer(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizer.State.began {
longPressGestureHandler?(recognizer)
}
}
@objc private func handleDoubleTapWithGestureRecognizer(_ recognizer: UITapGestureRecognizer) {
if photo.videoURL != nil || photo.localVideoURL != nil {
if playerController.videoGravity != .resizeAspectFill {
playerController.videoGravity = .resizeAspectFill
} else {
playerController.videoGravity = .resizeAspect
}
return
}
let pointInView = recognizer.location(in: scalingImageView.imageView)
var newZoomScale = scalingImageView.maximumZoomScale
if scalingImageView.zoomScale >= scalingImageView.maximumZoomScale || abs(scalingImageView.zoomScale - scalingImageView.maximumZoomScale) <= 0.01 {
newZoomScale = scalingImageView.minimumZoomScale
}
let scrollViewSize = scalingImageView.bounds.size
let width = scrollViewSize.width / newZoomScale
let height = scrollViewSize.height / newZoomScale
let originX = pointInView.x - (width / 2.0)
let originY = pointInView.y - (height / 2.0)
let rectToZoom = CGRect(x: originX, y: originY, width: width, height: height)
scalingImageView.zoom(to: rectToZoom, animated: true)
}
// MARK:- UIScrollViewDelegate
open func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scalingImageView.imageView
}
open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.panGestureRecognizer.isEnabled = true
}
open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
// There is a bug, especially prevalent on iPhone 6 Plus, that causes zooming to render all other gesture recognizers ineffective.
// This bug is fixed by disabling the pan gesture recognizer of the scroll view when it is not needed.
if (scrollView.zoomScale == scrollView.minimumZoomScale) {
scrollView.panGestureRecognizer.isEnabled = false;
}
}
}
| gpl-3.0 |
bingoogolapple/SwiftNote-PartOne | 九宫格新/九宫格新/ViewController.swift | 1 | 2735 | //
// ViewController.swift
// 九宫格新
//
// Created by bingoogol on 14/9/30.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
把素材放在bundle,可以允许在不同的bundle中中图片可以重名,实例化图片是需要指定bundle的名字
*/
let COL_COUNT = 5
let ROW_HEIGHT:CGFloat = 100
class ViewController: UIViewController,UITableViewDataSource,ProductCellDelegate {
let CELL_ID = "MyCell"
let PRODUCT_COUNT = 23
weak var tableView:UITableView!
var dataList:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
// 如果成员变量是weak的,则需要重新定义一个变量,然后赋值给成员变量
var tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
tableView.dataSource = self
// 表格的代理方法要少用
tableView.rowHeight = ROW_HEIGHT
// 取消分割线
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.view.addSubview(tableView)
self.tableView = tableView
// 初始化数据
var array = NSMutableArray(capacity: PRODUCT_COUNT)
var product:Product
for i in 0 ..< PRODUCT_COUNT {
product = Product.productWithName(NSString(format: "商品-%03d", i))
array.addObject(product)
}
self.dataList = array
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
/*
(1 - 1)/3 + 1 = 1
(2 - 1)/3 + 1 = 1
(3 - 1)/3 + 1 = 1
(4 - 1)/3 + 1 = 2
(5 - 1)/3 + 1 = 2
(6 - 1)/3 + 1 = 2
*/
return (self.dataList.count - 1) / COL_COUNT + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as ProductCell?
if cell == nil {
cell = ProductCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
cell?.delegate = self
}
var loc = indexPath.row * COL_COUNT
var avaliableLen = dataList.count - loc
var len = avaliableLen < COL_COUNT ? avaliableLen : COL_COUNT
var range = NSMakeRange(loc, len)
println("\(loc) \(avaliableLen) \(len)")
var array = self.dataList.subarrayWithRange(range)
cell?.cellRow = indexPath.row
cell?.resetButtonWithArray(array)
return cell!
}
func productCell(productCell: ProductCell, didSelectedAtIndex index: Int) {
var product = dataList[index] as Product
println("click \(product.name)")
}
} | apache-2.0 |
kstaring/swift | stdlib/public/SDK/CoreAudio/CoreAudio.swift | 4 | 6326 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreAudio // Clang module
extension UnsafeBufferPointer {
/// Initialize an `UnsafeBufferPointer<Element>` from an `AudioBuffer`.
/// Binds the buffer's memory type to `Element`.
public init(_ audioBuffer: AudioBuffer) {
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}
extension UnsafeMutableBufferPointer {
/// Initialize an `UnsafeMutableBufferPointer<Element>` from an
/// `AudioBuffer`.
public init(_ audioBuffer: AudioBuffer) {
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}
extension AudioBuffer {
/// Initialize an `AudioBuffer` from an
/// `UnsafeMutableBufferPointer<Element>`.
public init<Element>(
_ typedBuffer: UnsafeMutableBufferPointer<Element>,
numberOfChannels: Int
) {
self.mNumberChannels = UInt32(numberOfChannels)
self.mData = UnsafeMutableRawPointer(typedBuffer.baseAddress)
self.mDataByteSize = UInt32(typedBuffer.count * MemoryLayout<Element>.stride)
}
}
extension AudioBufferList {
/// - Returns: the size in bytes of an `AudioBufferList` that can hold up to
/// `maximumBuffers` `AudioBuffer`s.
public static func sizeInBytes(maximumBuffers: Int) -> Int {
_precondition(maximumBuffers >= 1,
"AudioBufferList should contain at least one AudioBuffer")
return MemoryLayout<AudioBufferList>.size +
(maximumBuffers - 1) * MemoryLayout<AudioBuffer>.stride
}
/// Allocate an `AudioBufferList` with a capacity for the specified number of
/// `AudioBuffer`s.
///
/// The `count` property of the new `AudioBufferList` is initialized to
/// `maximumBuffers`.
///
/// The memory should be freed with `free()`.
public static func allocate(maximumBuffers: Int)
-> UnsafeMutableAudioBufferListPointer {
let byteSize = sizeInBytes(maximumBuffers: maximumBuffers)
let ablMemory = calloc(byteSize, 1)
_precondition(ablMemory != nil,
"failed to allocate memory for an AudioBufferList")
let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1)
(ablMemory! + MemoryLayout<AudioBufferList>.stride).bindMemory(
to: AudioBuffer.self, capacity: maximumBuffers)
let abl = UnsafeMutableAudioBufferListPointer(listPtr)
abl.count = maximumBuffers
return abl
}
}
/// A wrapper for a pointer to an `AudioBufferList`.
///
/// Like `UnsafeMutablePointer`, this type provides no automated memory
/// management and the user must therefore take care to allocate and free
/// memory appropriately.
public struct UnsafeMutableAudioBufferListPointer {
/// Construct from an `AudioBufferList` pointer.
public init(_ p: UnsafeMutablePointer<AudioBufferList>) {
unsafeMutablePointer = p
}
/// Construct from an `AudioBufferList` pointer.
public init?(_ p: UnsafeMutablePointer<AudioBufferList>?) {
guard let unwrapped = p else { return nil }
self.init(unwrapped)
}
/// The number of `AudioBuffer`s in the `AudioBufferList`
/// (`mNumberBuffers`).
public var count: Int {
get {
return Int(unsafeMutablePointer.pointee.mNumberBuffers)
}
nonmutating set(newValue) {
unsafeMutablePointer.pointee.mNumberBuffers = UInt32(newValue)
}
}
/// The pointer to the first `AudioBuffer` in this `AudioBufferList`.
internal var _audioBuffersPointer: UnsafeMutablePointer<AudioBuffer> {
// AudioBufferList has one AudioBuffer in a "flexible array member".
// Position the pointer after that, and skip one AudioBuffer back. This
// brings us to the start of AudioBuffer array.
let rawPtr = UnsafeMutableRawPointer(unsafeMutablePointer + 1)
return rawPtr.assumingMemoryBound(to: AudioBuffer.self) - 1
}
// FIXME: the properties 'unsafePointer' and 'unsafeMutablePointer' should be
// initializers on UnsafePointer and UnsafeMutablePointer, but we don't want
// to allow any UnsafePointer<Element> to be initializable from an
// UnsafeMutableAudioBufferListPointer, only UnsafePointer<AudioBufferList>.
// We need constrained extensions for that. rdar://17821143
/// The pointer to the wrapped `AudioBufferList`.
public var unsafePointer: UnsafePointer<AudioBufferList> {
return UnsafePointer(unsafeMutablePointer)
}
/// The pointer to the wrapped `AudioBufferList`.
public var unsafeMutablePointer: UnsafeMutablePointer<AudioBufferList>
}
extension UnsafeMutableAudioBufferListPointer
: MutableCollection, RandomAccessCollection {
public typealias Index = Int
/// Always zero, which is the index of the first `AudioBuffer`.
public var startIndex: Int {
return 0
}
/// The "past the end" position; always identical to `count`.
public var endIndex: Int {
return count
}
/// Access an indexed `AudioBuffer` (`mBuffers[i]`).
public subscript(index: Int) -> AudioBuffer {
get {
_precondition(index >= 0 && index < self.count,
"subscript index out of range")
return (_audioBuffersPointer + index).pointee
}
nonmutating set(newValue) {
_precondition(index >= 0 && index < self.count,
"subscript index out of range")
(_audioBuffersPointer + index).pointee = newValue
}
}
public subscript(bounds: Range<Int>)
-> MutableRandomAccessSlice<UnsafeMutableAudioBufferListPointer> {
get {
return MutableRandomAccessSlice(base: self, bounds: bounds)
}
set {
_writeBackMutableSlice(&self, bounds: bounds, slice: newValue)
}
}
public typealias Indices = CountableRange<Int>
}
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/00988-swift-typechecker-typecheckdecl.swift | 11 | 518 | // 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
func a<T>: c<U -> {
struct e {
func d) {
return "cd"cd"A(self.d : d {
protocol a {
let h : AnyObject, c) {
}
}
func a((T.a: b
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.