repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hyperoslo/Orchestra
|
OrchestraTests/Specs/AudioPlayerSpec.swift
|
1
|
1415
|
import Quick
import Nimble
@testable import Orchestra
class AudioPlayerSpec: QuickSpec {
override func spec() {
describe("AudioPlayer") {
var audioPlayer: AudioPlayer!
context("when a theme bundle is not found") {
beforeEach {
let theme = Theme(
name: "Amazing",
audioFormat: "aiff")
audioPlayer = AudioPlayer(theme: theme)
}
describe(".play") {
it("should throw theme bundle not found error") {
expect { try audioPlayer.play(.Pop)}.to(
throwError(AudioPlayer.Error.ThemeBundleNotFound))
expect(audioPlayer.player).to(beNil())
}
}
describe(".playSafely") {
it("shouldn't start playing") {
let result = audioPlayer.playSafely(.Pop)
expect(result).to(beFalse())
}
}
describe(".resume") {
it("shouldn't resume") {
let result = audioPlayer.resume()
expect(result).to(beFalse())
}
}
describe(".stop") {
it("shouldn't stop") {
audioPlayer.stop()
expect(audioPlayer.player).to(beNil())
}
}
describe(".pause") {
it("shouldn't pause") {
let result = audioPlayer.pause()
expect(result).to(beFalse())
}
}
}
}
}
}
|
mit
|
f937c683a8ed00f6f68a2c2aaa0e5249
| 23.396552 | 64 | 0.50742 | 4.829352 | false | false | false | false |
rb-de0/tech.reb-dev.com
|
Sources/App/Models/DTO/Subcontent.swift
|
2
|
1856
|
import FluentProvider
import Validation
final class Subcontent: Model, JSONRepresentable {
let storage = Storage()
var name: String
var content: String
init(request: Request) throws {
name = request.data["name"]?.string ?? ""
content = request.data["content"]?.string ?? ""
try validate()
}
func validate() throws {
try name.validated(by: Count.containedIn(low: 1, high: 30))
try content.validated(by: Count.containedIn(low: 1, high: 10000))
}
required init(row: Row) throws {
name = try row.get("name")
content = try row.get("content")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("content", content)
return row
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("name", name)
try json.set("content", content)
return json
}
static func make(for parameter: String) throws -> Subcontent {
guard let subContent = try Subcontent.makeQuery().filter("name" == parameter).first() else {
throw Abort(.notFound, reason: "No \(Subcontent.self) with that identifier was found.")
}
return subContent
}
}
// MARK: - Preparation
extension Subcontent: Preparation {
static func prepare(_ database: Fluent.Database) throws {}
static func revert(_ database: Fluent.Database) throws {}
}
extension Subcontent: Updateable {
func update(for req: Request) throws {
name = req.data["name"]?.string ?? ""
content = req.data["content"]?.string ?? ""
try validate()
}
static var updateableKeys: [UpdateableKey<Subcontent>] {
return []
}
}
|
mit
|
79861a5a473f22dd89f7f67712e1345b
| 24.424658 | 100 | 0.568427 | 4.472289 | false | false | false | false |
CrazyZhangSanFeng/BanTang
|
BanTang/BanTang/Classes/Account/Controller/BTAccountViewController.swift
|
1
|
3909
|
//
// BTAccountViewController.swift
// BanTang
//
// Created by 张灿 on 16/5/23.
// Copyright © 2016年 张灿. All rights reserved.
//
import UIKit
class BTAccountViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
//添加导航栏两侧按钮
setNavButton()
//顶部个人信息
setupHeadView()
//背景色
tableView.backgroundColor = UIColor(red: 244 / 255.0, green: 244 / 255.0, blue: 244 / 255.0, alpha: 1.0)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 30
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 0.定义标示
let cellID = "CellID"
// 1.从缓冲池中取出cell
var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
// 2.判断是否取出cell
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellID)
}
// 3.给cell设置数据
cell?.textLabel?.text = "测试数据:\(indexPath.row)"
return cell!
}
//MARK:- 设置悬停view
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerSection = NSBundle.mainBundle().loadNibNamed("BTMiddleView", owner: nil, options: nil).first as! BTMiddleView
return headerSection
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
}
//MARK:- 导航栏两侧按钮
extension BTAccountViewController {
func setNavButton() {
//添加导航栏右侧按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "settingicon_44x44_"), style: .Plain, target: self, action: #selector(setClick))
//添加导航栏左侧按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "center_order_icon_44x44_"), style: .Done, target: self, action: #selector(centerClick))
navigationItem.leftBarButtonItem?.imageInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
navigationItem.rightBarButtonItem?.imageInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 15)
}
}
//MARK:- 导航栏按钮点击
extension BTAccountViewController {
func setClick() {
let storyboard = UIStoryboard.init(name: "BTSettingController", bundle: nil)
let setVC = storyboard.instantiateInitialViewController() as! BTSettingController
navigationController?.pushViewController(setVC, animated: true)
}
//订单点击
func centerClick() {
let storyboard = UIStoryboard.init(name: "BTOrderController", bundle: nil)
let orderVC = storyboard.instantiateInitialViewController() as! BTOrderController
navigationController?.pushViewController(orderVC, animated: true)
}
}
//MARK:- 个人信息头部视图
extension BTAccountViewController {
func setupHeadView() {
let headView = NSBundle.mainBundle().loadNibNamed("BTUserHeadView", owner: self, options: nil).first as! BTUserHeadView
headView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 132)
tableView.tableHeaderView = headView
}
}
|
apache-2.0
|
5b97abc332e30d914a2f1150b86dee3b
| 29.694215 | 169 | 0.639472 | 4.804657 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/Pods/Alamofire/Source/TaskDelegate.swift
|
42
|
15805
|
//
// TaskDelegate.swift
//
// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
public let queue: OperationQueue
/// The data returned by the server.
public var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
public var error: Error?
var task: URLSessionTask? {
set {
taskLock.lock(); defer { taskLock.unlock() }
_task = newValue
}
get {
taskLock.lock(); defer { taskLock.unlock() }
return _task
}
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
private var _task: URLSessionTask? {
didSet { reset() }
}
private let taskLock = NSLock()
// MARK: Lifecycle
init(task: URLSessionTask?) {
_task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
temporaryURL = location
guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }
let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options
self.destinationURL = destinationURL
do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
|
mit
|
f4f1be6e9e0ededface3260677960741
| 32.916309 | 149 | 0.662322 | 6.128344 | false | false | false | false |
insidegui/WWDC
|
WWDC/WWDCTabViewController.swift
|
1
|
6354
|
//
// WWDCTabViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 22/04/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RxSwift
import RxCocoa
class WWDCTabViewController<Tab: RawRepresentable>: NSTabViewController where Tab.RawValue == Int {
var activeTab: Tab {
get {
return Tab(rawValue: selectedTabViewItemIndex)!
}
set {
selectedTabViewItemIndex = newValue.rawValue
}
}
private var activeTabVar = BehaviorRelay<Tab>(value: Tab(rawValue: 0)!)
var rxActiveTab: Observable<Tab> {
return activeTabVar.asObservable()
}
override var selectedTabViewItemIndex: Int {
didSet {
guard selectedTabViewItemIndex != oldValue else { return }
guard selectedTabViewItemIndex >= 0 && selectedTabViewItemIndex < tabViewItems.count else { return }
tabViewItems.forEach { item in
guard let identifier = item.viewController?.identifier else { return }
guard let view = tabBar.items.first(where: { $0.controllerIdentifier == identifier.rawValue }) else { return }
if indexForChild(with: identifier.rawValue) == selectedTabViewItemIndex {
view.state = .on
} else {
view.state = .off
}
}
activeTabVar.accept(Tab(rawValue: selectedTabViewItemIndex)!)
}
}
private(set) lazy var tabBar = WWDCTabViewControllerTabBar()
init(windowController: WWDCWindowController) {
super.init(nibName: nil, bundle: nil)
windowController.titleBarViewController.tabBar = tabBar
// Preserve the window's size, essentially passing in saved window frame sizes
let superFrame = view.frame
if let windowFrame = windowController.window?.frame {
view.frame = NSRect(origin: superFrame.origin, size: windowFrame.size)
}
tabStyle = .unspecified
identifier = NSUserInterfaceItemIdentifier(rawValue: "tabs")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func addTabViewItem(_ tabViewItem: NSTabViewItem) {
super.addTabViewItem(tabViewItem)
let itemView = TabItemView(frame: .zero)
itemView.title = tabViewItem.label
itemView.controllerIdentifier = (tabViewItem.viewController?.identifier).map { $0.rawValue } ?? ""
itemView.image = NSImage(named: itemView.controllerIdentifier.lowercased())
itemView.alternateImage = NSImage(named: itemView.controllerIdentifier.lowercased() + "-filled")
itemView.sizeToFit()
itemView.target = self
itemView.action = #selector(changeTab)
itemView.state = (tabViewItems.firstIndex(of: tabViewItem) == selectedTabViewItemIndex) ? .on : .off
tabBar.addItem(itemView)
}
var isTopConstraintAdded = false
override func updateViewConstraints() {
super.updateViewConstraints()
// The top constraint keeps the tabView from extending
// under the title bar
if !isTopConstraintAdded, let window = view.window {
isTopConstraintAdded = true
NSLayoutConstraint(item: tabView,
attribute: .top,
relatedBy: .equal,
toItem: window.contentLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 0).isActive = true
}
}
override func transition(from fromViewController: NSViewController, to toViewController: NSViewController, options: NSViewController.TransitionOptions = [], completionHandler completion: (() -> Void)? = nil) {
// Disable the crossfade animation here instead of removing it from the transition options
// This works around a bug in NSSearchField in which the animation of resigning first responder
// would get stuck if you switched tabs while the search field was first responder. Upon returning
// to the original tab, you would see the search field's placeholder animate back to center
// search_field_responder_tag
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0
super.transition(from: fromViewController, to: toViewController, options: options, completionHandler: completion)
})
}
@objc
private func changeTab(_ sender: TabItemView) {
guard let index = indexForChild(with: sender.controllerIdentifier) else { return }
selectedTabViewItemIndex = index
}
private func indexForChild(with identifier: String) -> Int? {
return tabViewItems.firstIndex { $0.viewController?.identifier?.rawValue == identifier }
}
private var loadingView: ModalLoadingView?
func showLoading() {
loadingView = ModalLoadingView.show(attachedTo: view)
}
func hideLoading() {
loadingView?.hide()
}
private lazy var backgroundView: NSVisualEffectView = {
let v = NSVisualEffectView()
v.material = .headerView
v.state = .followsWindowActiveState
v.appearance = NSAppearance(named: .darkAqua)
v.blendingMode = .withinWindow
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidAppear() {
super.viewDidAppear()
installModernHeaderViewIfNeeded()
}
/// Puts a header view in the titlebar area when running on macOS 11 or later.
private func installModernHeaderViewIfNeeded() {
guard #available(macOS 11.0, *) else { return }
guard backgroundView.superview == nil else { return }
view.addSubview(backgroundView)
NSLayoutConstraint.activate([
backgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
backgroundView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
])
}
}
|
bsd-2-clause
|
04bb5ed6b7ee909185745a7aed5a3e8a
| 34.892655 | 213 | 0.642216 | 5.352148 | false | false | false | false |
OlegKetrar/Tools
|
Sources/Tools/UIKit/SliderAdapter.swift
|
1
|
4130
|
//
// SliderAdapter.swift
// ToolsUIKit
//
// Created by Oleg Ketrar on 05.03.17.
// Copyright © 2017 Oleg Ketrar. All rights reserved.
//
import Foundation
import UIKit
// TODO: add docs.
public final class SliderAdapter<Data, Cell: UICollectionViewCell>: NSObject,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDataSourcePrefetching,
UICollectionViewDelegateFlowLayout
where
Data: Equatable,
Cell: Reusable
{
private var countClosure: () -> Int = { 0 }
private var dataClosure: (Int) -> Data? = { _ in .none }
private var cellClosure: (Cell, Data) -> Cell = { (cell, _) in cell }
private var onSelectionClosure: (Int, Cell) -> Void = { _, _ in }
private var onPrefetchingClosure: (Int) -> Void = { _ in }
private var itemSizeClosure: ((Int, Data) -> CGSize)?
// MARK: - UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return countClosure()
}
public func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueCell(for: indexPath) as Cell
guard let data = dataClosure(indexPath.row) else { return cell }
return cellClosure(cell, data)
}
// MARK: - UICollectionViewDelegate
public func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? Cell else { return }
onSelectionClosure(indexPath.row, cell)
}
// MARK: - UICollectionViewDelegateFlowLayout
public func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
guard
let closure = itemSizeClosure,
let data = dataClosure(indexPath.row)
else {
return (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?
.itemSize ?? .zero
}
return closure(indexPath.row, data)
}
// MARK: - UICollectionViewDataSourcePrefetching
public func collectionView(
_ collectionView: UICollectionView,
prefetchItemsAt indexPaths: [IndexPath]) {
guard let index = indexPaths.first?.row else { return }
onPrefetchingClosure(index)
}
}
// MARK: - Configure
extension SliderAdapter {
@discardableResult
public func with(dataCount: @autoclosure @escaping () -> Int) -> Self {
countClosure = dataCount
return self
}
@discardableResult
public func onConfigure(_ closure: @escaping (Cell, Data) -> Cell) -> Self {
cellClosure = closure
return self
}
@discardableResult
public func onData(_ closure: @escaping (Int) -> Data?) -> Self {
dataClosure = closure
return self
}
@discardableResult
public func onSelection(_ closure: @escaping (Int, Cell) -> Void) -> Self {
onSelectionClosure = closure
return self
}
@discardableResult
public func onPrefetching(_ closure: @escaping (Int) -> Void) -> Self {
onPrefetchingClosure = closure
return self
}
@discardableResult
public func onCellSizing(_ closure: @escaping (Int, Data) -> CGSize) -> Self {
itemSizeClosure = closure
return self
}
}
// MARK: - UICollectionView Convenience
extension UICollectionView {
public typealias Adapter = UICollectionViewDataSource
& UICollectionViewDelegate
& UICollectionViewDataSourcePrefetching
@discardableResult
public func with(adapter: Adapter) -> Self {
dataSource = adapter
delegate = adapter
if #available(iOS 10.0, *) {
prefetchDataSource = adapter
}
return self
}
}
|
mit
|
f747f6770b48a0c0913a5cb90d128d9c
| 25.986928 | 91 | 0.650279 | 5.16125 | false | false | false | false |
tripleCC/GanHuoCode
|
GanHuo/Extension/UIFont+Extension.swift
|
1
|
3057
|
//
// UIFont+Extension.swift
// WKCC
//
// Created by tripleCC on 15/11/18.
// Copyright © 2015年 tripleCC. All rights reserved.
//
import UIKit
extension UIFont {
class func lanTingHeiSFontName() -> String {
return "FZLTXHK--GBK1-0"
}
class func lanTingHeiBFontName() -> String {
return "FZLTZHK--GBK1-0"
}
class func baskervilleSFontName() -> String {
return "Baskerville"
}
class func didotBFontName() -> String {
return "Didot-Bold"
}
class func avenirBookFontName() -> String {
return "Avenir-Book"
}
class func zapfinoName() -> String {
return "Zapfino"
}
class func hiraMinProNW3Name() -> String {
return "HiraMinProN-W3"
}
class func appleSDGothicNeoThinName() -> String {
return "AppleSDGothicNeo-Thin"
}
class func appleSDGothicNeoUltraLight() -> String {
return "AppleSDGothicNeo-UltraLight"
}
class func showAllFonts() -> [String] {
var fontNamesSaver = [String]()
let familyNames = self.familyNames()
for familyName in familyNames {
print("Family: \(familyName) \n")
let fontNames = UIFont.fontNamesForFamilyName(familyName)
for fontName in fontNames {
print("\tFont: \(fontName) \n")
fontNamesSaver.append(fontName)
}
}
return fontNamesSaver
}
class func createAllTypeIcon() {
let fontNames = UIFont.showAllFonts()
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
containerView.backgroundColor = UIColor.whiteColor()
let circleView = UIView(frame: containerView.bounds)
circleView.bounds.size.width -= 10
circleView.bounds.size.height -= 10
containerView.addSubview(circleView)
circleView.center = containerView.center
circleView.layer.cornerRadius = circleView.bounds.width * 0.5
circleView.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(1)
let mainLabel = UILabel(frame: CGRect(x: 0, y: 0, width: containerView.frame.width, height: containerView.frame.height * 0.7))
mainLabel.center = containerView.center
mainLabel.textColor = UIColor.whiteColor()
containerView.addSubview(mainLabel)
mainLabel.text = "huo"
mainLabel.textAlignment = NSTextAlignment.Center
for fontName in fontNames {
mainLabel.font = UIFont(name: fontName, size: 22)
let data = UIImagePNGRepresentation(UIImage(layer: containerView.layer))
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] + "\(fontName).png"
print(path)
data?.writeToFile(path, atomically: true)
}
}
}
}
|
mit
|
5d37829ac83bfbb30075a595747792c7
| 32.206522 | 169 | 0.617223 | 4.705701 | false | false | false | false |
suzp1984/IOS-ApiDemo
|
ApiDemo-Swift/ApiDemo-Swift/ImageResolutionViewController.swift
|
1
|
3303
|
//
// ImageResolutionViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 5/11/16.
// Copyright © 2016 [email protected]. All rights reserved.
//
import UIKit
class ImageResolutionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
let iv1 = UIImageView()
iv1.translatesAutoresizingMaskIntoConstraints = false
iv1.widthAnchor.constraint(equalToConstant: 122).isActive = true
iv1.heightAnchor.constraint(equalToConstant: 122).isActive = true
let iv2 = UIImageView()
iv2.translatesAutoresizingMaskIntoConstraints = false
iv2.widthAnchor.constraint(equalToConstant: 122).isActive = true
iv2.heightAnchor.constraint(equalToConstant: 122).isActive = true
let iv3 = UIImageView()
iv3.translatesAutoresizingMaskIntoConstraints = false
iv3.widthAnchor.constraint(equalToConstant: 122).isActive = true
iv3.heightAnchor.constraint(equalToConstant: 122).isActive = true
let iv4 = UIImageView()
iv4.translatesAutoresizingMaskIntoConstraints = false
iv4.widthAnchor.constraint(equalToConstant: 122).isActive = true
iv4.heightAnchor.constraint(equalToConstant: 122).isActive = true
self.view.addSubview(iv1)
self.view.addSubview(iv2)
self.view.addSubview(iv3)
self.view.addSubview(iv4)
iv1.image = UIImage(named: "one")
iv2.image = UIImage(named: "uno")
if let s = Bundle.main.path(forResource: "one", ofType: "png") {
iv3.image = UIImage(contentsOfFile: s)
}
if let s2 = Bundle.main.path(forResource: "uno", ofType: "png") {
iv4.image = UIImage(contentsOfFile: s2)
} else {
print("looking for smiley")
iv4.image = UIImage(named:"smiley")
}
NSLayoutConstraint.activate([
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[iv1]-(10)-[iv2]", options: [], metrics: nil, views: ["iv1":iv1, "iv2":iv2]),
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[iv3]-(10)-[iv4]", options: [], metrics: nil, views: ["iv3":iv3, "iv4":iv4]),
NSLayoutConstraint.constraints(withVisualFormat: "V:|[tlg]-(10)-[iv1]-(10)-[iv3]", options: [], metrics: nil, views: ["iv1":iv1, "iv3":iv3, "tlg":self.topLayoutGuide]),
NSLayoutConstraint.constraints(withVisualFormat: "V:|[tlg]-(10)-[iv2]-(10)-[iv4]", options: [], metrics: nil, views: ["iv2":iv2, "iv4":iv4, "tlg": self.topLayoutGuide])
].flatMap{$0})
}
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.
}
*/
}
|
apache-2.0
|
b078e42ca9f367029f1ce7a40af68ebf
| 39.765432 | 180 | 0.643247 | 4.450135 | false | false | false | false |
ascode/JF-IOS-Swift_demos
|
IOSDemos/Controller/UITableViewDemos/SimpleTableViewController.swift
|
1
|
1540
|
//
// SimpleTableViewController.swift
// IOSDemos
//
// Created by 金飞 on 29/12/2016.
// Copyright © 2016 Enjia. All rights reserved.
//
import UIKit
class SimpleTableViewController: UIViewController, SimpleTableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let kselfviewW: CGFloat = UIScreen.main.bounds.width
let kselfviewH: CGFloat = UIScreen.main.bounds.height - UIApplication.shared.statusBarFrame.height
let kselfviewX: CGFloat = UIScreen.main.bounds.origin.x
let kselfviewY: CGFloat = UIScreen.main.bounds.origin.y + UIApplication.shared.statusBarFrame.height
let selfview: SimpleTableView = SimpleTableView(frame: CGRect(x: kselfviewX, y: kselfviewY, width: kselfviewW, height: kselfviewH))
selfview.backgroundColor = UIColor.white
selfview._delegate = self
self.view = selfview
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func btnBackPressed(btnObj: UIButton){
self.dismiss(animated: true) {
}
}
/*
// 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.
}
*/
}
|
artistic-2.0
|
2a106d2feaf4fb52a9f5dd63a8595233
| 31.659574 | 139 | 0.685342 | 4.449275 | false | false | false | false |
dusanIntellex/backend-operation-layer
|
Example/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift
|
1
|
2328
|
//
// AsyncLock.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/**
In case nobody holds this lock, the work will be queued and executed immediately
on thread that is requesting lock.
In case there is somebody currently holding that lock, action will be enqueued.
When owned of the lock finishes with it's processing, it will also execute
and pending work.
That means that enqueued work could possibly be executed later on a different thread.
*/
final class AsyncLock<I: InvocableType>
: Disposable
, Lock
, SynchronizedDisposeType {
typealias Action = () -> Void
var _lock = SpinLock()
private var _queue: Queue<I> = Queue(capacity: 0)
private var _isExecuting: Bool = false
private var _hasFaulted: Bool = false
// lock {
func lock() {
_lock.lock()
}
func unlock() {
_lock.unlock()
}
// }
private func enqueue(_ action: I) -> I? {
_lock.lock(); defer { _lock.unlock() } // {
if _hasFaulted {
return nil
}
if _isExecuting {
_queue.enqueue(action)
return nil
}
_isExecuting = true
return action
// }
}
private func dequeue() -> I? {
_lock.lock(); defer { _lock.unlock() } // {
if !_queue.isEmpty {
return _queue.dequeue()
}
else {
_isExecuting = false
return nil
}
// }
}
func invoke(_ action: I) {
let firstEnqueuedAction = enqueue(action)
if let firstEnqueuedAction = firstEnqueuedAction {
firstEnqueuedAction.invoke()
}
else {
// action is enqueued, it's somebody else's concern now
return
}
while true {
let nextAction = dequeue()
if let nextAction = nextAction {
nextAction.invoke()
}
else {
return
}
}
}
func dispose() {
synchronizedDispose()
}
func _synchronized_dispose() {
_queue = Queue(capacity: 0)
_hasFaulted = true
}
}
|
mit
|
f6ddca3b03dc186f5bfed2da89b400b3
| 21.813725 | 85 | 0.522131 | 4.797938 | false | false | false | false |
steelwheels/KiwiScript
|
KiwiEngine/Source/KECompiler.swift
|
1
|
3712
|
/**
* @file KECompiler.swift
* @brief Define KECompiler class
* @par Copyright
* Copyright (C) 2015 Steel Wheels Project
*/
import CoconutData
import JavaScriptCore
import Foundation
open class KECompiler
{
public init(){
}
public func compileBase(context ctxt: KEContext, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNFileConsole, config conf: KEConfig) -> Bool {
/* Set strict */
setStrictMode(context: ctxt, console: cons, config: conf)
/* Define Enum Types */
compileEnumTables(context: ctxt, console: cons, config: conf)
return true
}
private func setStrictMode(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig){
if conf.doStrict {
let srcfile = URL(fileURLWithPath: #file)
let _ = compileStatement(context: ctxt, statement: "'use strict' ;\n", sourceFile: srcfile, console: cons, config: conf)
}
}
private func compileEnumTables(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) {
for etable in CNEnumTable.allEnumTables() {
let scr = etable.toScript().toStrings().joined(separator: "\n")
let srcfile = URL(fileURLWithPath: #file)
let _ = compileStatement(context: ctxt, statement: scr, sourceFile: srcfile, console: cons, config: conf)
}
}
public func compileStatement(context ctxt: KEContext, statement stmt: String, sourceFile srcfile: URL?, console cons: CNConsole, config conf: KEConfig) -> JSValue? {
switch conf.logLevel {
case .nolog, .error, .warning, .debug:
break
case .detail:
cons.print(string: stmt)
@unknown default:
break
}
return ctxt.evaluateScript(script: stmt, sourceFile: srcfile)
}
public func compileStatements(context ctxt: KEContext, statements stmts: Array<String>, sourceFile srcfile: URL?, console cons: CNConsole, config conf: KEConfig) -> JSValue? {
let script = stmts.joined(separator: "\n")
switch conf.logLevel {
case .nolog, .error, .warning, .debug:
break
case .detail:
cons.print(string: script)
@unknown default:
break
}
return ctxt.evaluateScript(script: script, sourceFile: srcfile)
}
private func compileEnumType(context ctxt: KEContext, enumType etype: CNEnumType, console cons: CNConsole, config conf: KEConfig){
/* Compile */
let typename = etype.typeName
switch conf.logLevel {
case .nolog, .error, .warning, .debug:
break
case .detail:
cons.print(string: "/* Define Enum: \(typename) */\n")
@unknown default:
break
}
var enumstmt = "let \(typename) = {\n"
var is1st = true
for name in etype.names {
if let value = etype.value(forMember: name) {
if !is1st {
enumstmt += ",\n"
}
is1st = false
enumstmt += "\t\(name) : \(value)"
} else {
CNLog(logLevel: .error, message: "Can not happen", atFunction: #function, inFile: #file)
}
}
enumstmt += "\n};\n"
let srcfile = URL(fileURLWithPath: #file)
let _ = compileStatement(context: ctxt, statement: enumstmt, sourceFile: srcfile, console: cons, config: conf)
}
public func compileDictionaryVariable(context ctxt: KEContext, destination dst: String, dictionary dict: Dictionary<String, String>, console cons: CNConsole, config conf: KEConfig){
var stmt = "\(dst) = {\n"
var is1st = true
for (key, value) in dict {
if is1st {
is1st = false
} else {
stmt = ",\n"
}
stmt += "\t\(key): \(value)"
}
stmt += "\n};\n"
let srcfile = URL(fileURLWithPath: #file)
let _ = compileStatement(context: ctxt, statement: stmt, sourceFile: srcfile, console: cons, config: conf)
}
private func message(fromError err: NSError?) -> String {
if let e = err {
return e.toString()
} else {
return "Unknown error"
}
}
}
|
lgpl-2.1
|
17615077371ac318b46d2206dba0dfaa
| 29.933333 | 182 | 0.687231 | 3.329148 | false | true | false | false |
atl009/WordPress-iOS
|
WordPress/Classes/ViewRelated/NUX/SignupViewController.swift
|
1
|
20948
|
import UIKit
import CocoaLumberjack
import WordPressShared
/// Create a new WordPress.com account and blog.
///
@objc class SignupViewController: NUXAbstractViewController, SigninKeyboardResponder {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var emailField: WPWalkthroughTextField!
@IBOutlet weak var usernameField: WPWalkthroughTextField!
@IBOutlet weak var passwordField: WPWalkthroughTextField!
@IBOutlet weak var siteURLField: WPWalkthroughTextField!
@IBOutlet weak var submitButton: NUXSubmitButton!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var termsButton: UIButton!
@IBOutlet var bottomContentConstraint: NSLayoutConstraint?
@IBOutlet var verticalCenterConstraint: NSLayoutConstraint?
@IBOutlet var topLayoutGuideAdjustmentConstraint: NSLayoutConstraint!
@IBOutlet var formTopMarginConstraint: NSLayoutConstraint!
var onePasswordButton: UIButton!
var didCorrectEmailOnce: Bool = false
var userDefinedSiteAddress: Bool = false
let operationQueue = OperationQueue()
var account: WPAccount?
let LanguageIDKey = "lang_id"
let BlogDetailsKey = "blog_details"
let BlogNameLowerCaseNKey = "blogname"
let BlogNameUpperCaseNKey = "blogName"
let XMLRPCKey = "xmlrpc"
let BlogIDKey = "blogid"
let URLKey = "url"
let nonAlphanumericCharacterSet = NSCharacterSet.alphanumerics.inverted
override var sourceTag: SupportSourceTag {
get {
return .wpComSignup
}
}
/// A convenience method for obtaining an instance of the controller from a storyboard.
///
class func controller() -> SignupViewController {
let storyboard = UIStoryboard(name: "Login", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController
return controller
}
// MARK: - Lifecycle Methods
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
WPAppAnalytics.track(.createAccountInitiated)
}
override func viewDidLoad() {
super.viewDidLoad()
setupStyles()
localizeControls()
configureTermsButtonText()
setupOnePasswordButtonIfNeeded()
displayLoginMessage("")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Update special case login fields.
loginFields.meta.userIsDotCom = true
emailField.text = loginFields.emailAddress
configureLayoutForSmallScreensIfNeeded()
configureSubmitButton(animating: false)
configureViewForEditingIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
registerForKeyboardEvents(keyboardWillShowAction: #selector(handleKeyboardWillShow(_:)),
keyboardWillHideAction: #selector(handleKeyboardWillHide(_:)))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unregisterForKeyboardEvents()
}
// MARK: Setup and Configuration
/// Adjust the layout for smaller screens, specifically the iPhone 4s
///
func configureLayoutForSmallScreensIfNeeded() {
if !shouldAdjustLayoutForSmallScreen() {
return
}
// Remove the negative layout adjustment
topLayoutGuideAdjustmentConstraint.constant = 0
// Hide the logo
logoImageView.isHidden = true
// Remove the title label to also remove unwanted constraints.
if titleLabel.superview != nil {
titleLabel.removeFromSuperview()
}
}
/// Assigns localized strings to various UIControl defined in the storyboard.
///
func localizeControls() {
titleLabel.text = NSLocalizedString("Create an account on WordPress.com", comment: "Title of a screen")
emailField.placeholder = NSLocalizedString("Email Address", comment: "Email address placeholder")
usernameField.placeholder = NSLocalizedString("Username", comment: "Username placeholder")
passwordField.placeholder = NSLocalizedString("Password", comment: "Password placeholder")
siteURLField.placeholder = NSLocalizedString("Site Address (URL)", comment: "Site Address placeholder")
let submitButtonTitle = NSLocalizedString("Create Account", comment: "Title of a button. The text should be uppercase.").localizedUppercase
submitButton.setTitle(submitButtonTitle, for: UIControlState())
submitButton.setTitle(submitButtonTitle, for: .highlighted)
}
/// Sets up a 1Password button if 1Password is available.
///
func setupOnePasswordButtonIfNeeded() {
WPStyleGuide.configureOnePasswordButtonForTextfield(usernameField,
target: self,
selector: #selector(SignupViewController.handleOnePasswordButtonTapped(_:)))
}
/// Configures the appearance of the Terms button.
///
func configureTermsButtonText() {
let string = NSLocalizedString("By creating an account you agree to the fascinating <u>Terms of Service</u>.",
comment: "Message displayed when a verification code is needed")
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
let styledString = "<style>body {font-family: -apple-system, sans-serif; font-size:13px; color: #ffffff; text-align:center;}</style>" + string
guard let data = styledString.data(using: String.Encoding.utf8),
let attributedCode = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil),
let attributedCodeHighlighted = attributedCode.mutableCopy() as? NSMutableAttributedString
else {
return
}
attributedCodeHighlighted.applyForegroundColor(WPNUXUtility.confirmationLabelColor())
if let titleLabel = termsButton.titleLabel {
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 3
}
termsButton.setAttributedTitle(attributedCode, for: UIControlState())
termsButton.setAttributedTitle(attributedCodeHighlighted, for: .highlighted)
}
/// Configures the appearance and state of the submit button.
///
func configureSubmitButton(animating: Bool) {
submitButton.showActivityIndicator(animating)
submitButton.isEnabled = (
!animating &&
!loginFields.emailAddress.isEmpty &&
!loginFields.username.isEmpty &&
!loginFields.password.isEmpty &&
!loginFields.siteAddress.isEmpty
)
}
/// Sets the view's state to loading or not loading.
///
/// - Parameters:
/// - loading: True if the form should be configured to a "loading" state.
///
func configureLoading(_ loading: Bool) {
emailField.isEnabled = !loading
usernameField.isEnabled = !loading
passwordField.isEnabled = !loading
siteURLField.isEnabled = !loading
configureSubmitButton(animating: loading)
navigationItem.hidesBackButton = loading
}
/// Configure the view for an editing state. Should only be called from viewWillAppear
/// as this method skips animating any change in height.
///
func configureViewForEditingIfNeeded() {
// Check the helper to determine whether an editiing state should be assumed.
adjustViewForKeyboard(SigninEditingState.signinEditingStateActive)
if SigninEditingState.signinEditingStateActive {
emailField.becomeFirstResponder()
}
}
// MARK: - Instance Methods
/// Sets up the view's colors and style
open func setupStyles() {
WPStyleGuide.configureColorsForSigninView(view)
}
/// Whether the view layout should be adjusted for smaller screens
///
/// - Returns true if the window height matches the height of the iPhone 4s (480px).
/// NOTE: NUX layout assumes a portrait orientation only.
///
func shouldAdjustLayoutForSmallScreen() -> Bool {
guard let window = UIApplication.shared.keyWindow else {
return false
}
return window.frame.height <= 480
}
/// Displays an alert prompting that a site address is needed before 1Password can be used.
///
func displayOnePasswordEmptySiteAlert() {
let message = NSLocalizedString("A site address is required before 1Password can be used.",
comment: "Error message displayed when the user is Signing into a self hosted site and tapped the 1Password Button before typing his siteURL")
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addCancelActionWithTitle(NSLocalizedString("OK", comment: "OK Button Title"), handler: nil)
present(alertController, animated: true, completion: nil)
}
/// Display an authentication status message
///
/// - Parameters:
/// - message: The message to display
///
func displayLoginMessage(_ message: String!) {
statusLabel.text = message
}
/// Display an authentication status message
///
/// - Parameters:
/// - message: The message to display
///
/// - Returns: the generated username
///
func generateSiteTitleFromUsername(_ username: String) -> String {
// Currently, we set the title of a new site to the username of the account.
// Another possibility would be to name the site "username's blog", which is
// why this has been placed in a separate method.
return username
}
/// Validates what is entered in the various form fields and, if valid,
/// proceeds with the submit action.
///
func validateForm() {
view.endEditing(true)
// Is everything filled out?
if !SigninHelpers.validateFieldsPopulatedForCreateAccount(loginFields) {
displayErrorAlert(NSLocalizedString("Please fill out all the fields", comment: "A short prompt asking the user to properly fill out all login fields."), sourceTag: sourceTag)
return
}
if !SigninHelpers.validateFieldsForSigninContainNoSpaces(loginFields) {
displayErrorAlert(NSLocalizedString("Email, Username, and Site Address cannot contain spaces.", comment: "No spaces error message."), sourceTag: sourceTag)
return
}
if !SigninHelpers.validateUsernameMaxLength(loginFields.username) {
displayErrorAlert(NSLocalizedString("Username must be less than fifty characters.", comment: "Prompts that the username entered was too long."), sourceTag: sourceTag)
usernameField.becomeFirstResponder()
return
}
if !loginFields.emailAddress.isValidEmail() {
displayErrorAlert(NSLocalizedString("Please enter a valid email address", comment: "A short prompt asking the user to properly fill out all login fields."), sourceTag: sourceTag)
emailField.becomeFirstResponder()
return
}
// Remove ".wordpress.com" if it was entered.
loginFields.siteAddress = loginFields.siteAddress.components(separatedBy: ".")[0]
configureLoading(true)
createAccountAndSite()
}
/// Because the signup form is larger than the average sign in form and has
/// a header, we want to tweak the vertical offset a bit rather than use
/// the default.
/// However, on a small screen we remove some UI elements so return the default size.
///
/// - Returns: The offset to apply to the form
///
func signinFormVerticalOffset() -> CGFloat {
if shouldAdjustLayoutForSmallScreen() {
return DefaultSigninFormVerticalOffset
}
return -24.0
}
/// Create the account and the site. Call this after everything passes validation.
///
func createAccountAndSite() {
let statusBlock = { (status: SignupStatus) in
self.displayLoginMessageForStatus(status)
}
let successBlock = {
self.displayLoginMessage("")
self.configureLoading(false)
self.dismiss()
}
let failureBlock = { (error: Error?) in
self.displayLoginMessage("")
self.configureLoading(false)
if let error = error as NSError? {
self.displayError(error, sourceTag: self.sourceTag)
}
}
let context = ContextManager.sharedInstance().mainContext
let service = SignupService(managedObjectContext: context)
service.createBlogAndSigninToWPCom(blogURL: loginFields.siteAddress,
blogTitle: loginFields.username,
emailAddress: loginFields.emailAddress,
username: loginFields.username,
password: loginFields.password,
status: statusBlock,
success: successBlock,
failure: failureBlock)
}
/// Display a status message for the specified SignupStatus
///
/// - Paramaters:
/// - status: SignupStatus
///
func displayLoginMessageForStatus(_ status: SignupStatus) {
switch status {
case .validating :
displayLoginMessage(NSLocalizedString("Validating", comment: "Short status message shown to the user when validating a new blog's name."))
break
case .creatingUser :
displayLoginMessage(NSLocalizedString("Creating account", comment: "Brief status message shown to the user when creating a new wpcom account."))
break
case .authenticating :
displayLoginMessage(NSLocalizedString("Authenticating", comment: "Brief status message shown when signing into a newly created blog and account."))
break
case .creatingBlog :
displayLoginMessage(NSLocalizedString("Creating site", comment: "Short status message shown while a new site is being created for a new user."))
break
case .syncing :
displayLoginMessage(NSLocalizedString("Syncing account information", comment: "Short status message shown while blog and account information is being synced."))
break
}
}
// MARK: - Actions
@IBAction func handleTextFieldDidChange(_ sender: UITextField) {
// Ensure that username and site fields are lower cased.
if sender == usernameField || sender == siteURLField {
sender.text = sender.text?.lowercased()
}
loginFields.emailAddress = emailField.nonNilTrimmedText()
loginFields.username = usernameField.nonNilTrimmedText()
loginFields.password = passwordField.nonNilTrimmedText()
loginFields.siteAddress = siteURLField.nonNilTrimmedText()
configureSubmitButton(animating: false)
}
@IBAction func handleSubmitButtonTapped(_ sender: UIButton) {
validateForm()
}
func handleOnePasswordButtonTapped(_ sender: UIButton) {
view.endEditing(true)
OnePasswordFacade().createLogin(forURLString: WPOnePasswordWordPressComURL,
username: loginFields.username,
password: loginFields.password,
for: self,
sender: sender,
completion: { (username, password, error: Error?) in
if let error = error as NSError? {
if error.code != WPOnePasswordErrorCodeCancelledByUser {
DDLogError("Failed to use 1Password App Extension to save a new Login: \(error)")
WPAnalytics.track(.onePasswordFailed)
}
return
}
if let username = username {
self.loginFields.username = username
self.usernameField.text = username
}
if let password = password {
self.loginFields.password = password
self.passwordField.text = password
}
WPAnalytics.track(.onePasswordSignup)
// Note: Since the Site field is right below the 1Password field, let's continue with the edition flow
// and make the SiteAddress Field the first responder.
self.siteURLField.becomeFirstResponder()
})
}
@IBAction func handleTermsOfServiceButtonTapped(_ sender: UIButton) {
let url = URL(string: WPAutomatticTermsOfServiceURL)!
let controller = WebViewControllerFactory.controller(url: url)
let navController = RotationAwareNavigationViewController(rootViewController: controller)
present(navController, animated: true, completion: nil)
}
// MARK: - Keyboard Notifications
func handleKeyboardWillShow(_ notification: Foundation.Notification) {
keyboardWillShow(notification)
}
func handleKeyboardWillHide(_ notification: Foundation.Notification) {
keyboardWillHide(notification)
}
}
extension SignupViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailField {
usernameField.becomeFirstResponder()
} else if textField == usernameField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
siteURLField.becomeFirstResponder()
} else if submitButton.isEnabled {
validateForm()
}
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if textField != emailField || didCorrectEmailOnce {
return true
}
guard let email = textField.text else {
return true
}
let suggestedEmail = EmailTypoChecker.guessCorrection(email: email)
if suggestedEmail != textField.text {
textField.text = suggestedEmail
didCorrectEmailOnce = true
loginFields.emailAddress = textField.nonNilTrimmedText()
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField != usernameField || userDefinedSiteAddress {
return
}
// If the user has not customized the site name, then let it match the
// username they chose.
loginFields.siteAddress = loginFields.username
siteURLField.text = loginFields.username
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Disallow spaces except for the password field
if string == " " && (textField == emailField || textField == usernameField || textField == siteURLField) {
return false
}
// Disallow punctuation in username and site names
if textField == usernameField || textField == siteURLField {
if (string as NSString).rangeOfCharacter(from: nonAlphanumericCharacterSet).location != NSNotFound {
return false
}
}
if textField == siteURLField {
userDefinedSiteAddress = true
}
return true
}
}
|
gpl-2.0
|
75d3739ced40639d533a690739753936
| 37.936803 | 190 | 0.618293 | 5.88427 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/YPImagePicker/Source/Helpers/Extensions/CGRect+Extensions.swift
|
3
|
1975
|
//
// CGRect+Difference.swift
// YPImagePicker
//
// Created by Sacha DSO on 26/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
internal extension CGRect {
func differenceWith(rect: CGRect,
removedHandler: (CGRect) -> Void,
addedHandler: (CGRect) -> Void) {
if rect.intersects(self) {
let oldMaxY = self.maxY
let oldMinY = self.minY
let newMaxY = rect.maxY
let newMinY = rect.minY
if newMaxY > oldMaxY {
let rectToAdd = CGRect(x: rect.origin.x,
y: oldMaxY,
width: rect.size.width,
height: (newMaxY - oldMaxY))
addedHandler(rectToAdd)
}
if oldMinY > newMinY {
let rectToAdd = CGRect(x: rect.origin.x,
y: newMinY,
width: rect.size.width,
height: (oldMinY - newMinY))
addedHandler(rectToAdd)
}
if newMaxY < oldMaxY {
let rectToRemove = CGRect(x: rect.origin.x,
y: newMaxY,
width: rect.size.width,
height: (oldMaxY - newMaxY))
removedHandler(rectToRemove)
}
if oldMinY < newMinY {
let rectToRemove = CGRect(x: rect.origin.x,
y: oldMinY,
width: rect.size.width,
height: (newMinY - oldMinY))
removedHandler(rectToRemove)
}
} else {
addedHandler(rect)
removedHandler(self)
}
}
}
|
mit
|
1867f52431905c84a1d3e8a1e7e7cbe9
| 35.555556 | 70 | 0.408308 | 5.64 | false | false | false | false |
eure/ReceptionApp
|
iOS/Pods/CoreStore/CoreStore/Saving and Processing/BaseDataTransaction.swift
|
1
|
19970
|
//
// BaseDataTransaction.swift
// CoreStore
//
// Copyright © 2014 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - BaseDataTransaction
/**
The `BaseDataTransaction` is an abstract interface for `NSManagedObject` creates, updates, and deletes. All `BaseDataTransaction` subclasses manage a private `NSManagedObjectContext` which are direct children of the `NSPersistentStoreCoordinator`'s root `NSManagedObjectContext`. This means that all updates are saved first to the persistent store, and then propagated up to the read-only `NSManagedObjectContext`.
*/
public /*abstract*/ class BaseDataTransaction {
// MARK: Object management
/**
Indicates if the transaction has pending changes
*/
public var hasChanges: Bool {
return self.context.hasChanges
}
/**
Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
public func create<T: NSManagedObject>(into: Into<T>) -> T {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to create an entity of type \(typeName(T)) outside its designated queue."
)
let context = self.context
let entityClass = (into.entityClass as! NSManagedObject.Type)
if into.inferStoreIfPossible {
switch context.parentStack!.persistentStoreForEntityClass(entityClass, configuration: nil, inferStoreIfPossible: true) {
case (let persistentStore?, _):
let object = entityClass.createInContext(context) as! T
context.assignObject(object, toPersistentStore: persistentStore)
return object
case (.None, true):
fatalError("Attempted to create an entity of type \(typeName(entityClass)) with ambiguous destination persistent store, but the configuration name was not specified.")
default:
fatalError("Attempted to create an entity of type \(typeName(entityClass)), but a destination persistent store containing the entity type could not be found.")
}
}
else {
switch context.parentStack!.persistentStoreForEntityClass(entityClass, configuration: into.configuration, inferStoreIfPossible: false) {
case (let persistentStore?, _):
let object = entityClass.createInContext(context) as! T
context.assignObject(object, toPersistentStore: persistentStore)
return object
default:
if let configuration = into.configuration {
fatalError("Attempted to create an entity of type \(typeName(entityClass)) into the configuration \"\(configuration)\", which it doesn't belong to.")
}
else {
fatalError("Attempted to create an entity of type \(typeName(entityClass)) into the default configuration, which it doesn't belong to.")
}
}
}
}
/**
Returns an editable proxy of a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public func edit<T: NSManagedObject>(object: T?) -> T? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to update an entity of type \(typeName(object)) outside its designated queue."
)
guard let object = object else {
return nil
}
return self.context.fetchExisting(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public func edit<T: NSManagedObject>(into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to update an entity of type \(typeName(T)) outside its designated queue."
)
CoreStore.assert(
into.inferStoreIfPossible
|| (into.configuration ?? Into.defaultConfigurationName) == objectID.persistentStore?.configurationName,
"Attempted to update an entity of type \(typeName(T)) but the specified persistent store do not match the `NSManagedObjectID`."
)
return self.fetchExisting(objectID) as? T
}
/**
Deletes a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` to be deleted
*/
public func delete(object: NSManagedObject?) {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete an entity outside its designated queue."
)
guard let object = object else {
return
}
self.context.fetchExisting(object)?.deleteFromContext()
}
/**
Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` to be deleted
- parameter object2: another `NSManagedObject` to be deleted
- parameter objects: other `NSManagedObject`s to be deleted
*/
public func delete(object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
self.delete(([object1, object2] + objects).flatMap { $0 })
}
/**
Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted
*/
public func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete entities outside their designated queue."
)
let context = self.context
objects.forEach { context.fetchExisting($0)?.deleteFromContext() }
}
/**
Refreshes all registered objects `NSManagedObject`s in the transaction.
*/
public func refreshAllObjectsAsFaults() {
CoreStore.assert(
self.isRunningInAllowedQueue(),
"Attempted to refresh entities outside their designated queue."
)
self.context.refreshAllObjectsAsFaults()
}
// MARK: Inspecting Pending Objects
/**
Returns all pending `NSManagedObject`s that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObject`s that were inserted to the transaction.
*/
public func insertedObjects() -> Set<NSManagedObject> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access inserted objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access inserted objects from an already committed \(typeName(self))."
)
return self.context.insertedObjects
}
/**
Returns all pending `NSManagedObject`s of the specified type that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were inserted to the transaction.
*/
public func insertedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access inserted objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access inserted objects from an already committed \(typeName(self))."
)
return Set(self.context.insertedObjects.flatMap { $0 as? T })
}
/**
Returns all pending `NSManagedObjectID`s that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObjectID`s that were inserted to the transaction.
*/
public func insertedObjectIDs() -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access inserted object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access inserted objects IDs from an already committed \(typeName(self))."
)
return Set(self.context.insertedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction.
*/
public func insertedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access inserted object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access inserted objects IDs from an already committed \(typeName(self))."
)
return Set(self.context.insertedObjects.flatMap { $0 as? T }.map { $0.objectID })
}
/**
Returns all pending `NSManagedObject`s that were updated in the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObject`s that were updated to the transaction.
*/
public func updatedObjects() -> Set<NSManagedObject> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access updated objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access updated objects from an already committed \(typeName(self))."
)
return self.context.updatedObjects
}
/**
Returns all pending `NSManagedObject`s of the specified type that were updated in the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were updated in the transaction.
*/
public func updatedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access updated objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access updated objects from an already committed \(typeName(self))."
)
return Set(self.context.updatedObjects.flatMap { $0 as? T })
}
/**
Returns all pending `NSManagedObjectID`s that were updated in the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObjectID`s that were updated in the transaction.
*/
public func updatedObjectIDs() -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access updated object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access updated object IDs from an already committed \(typeName(self))."
)
return Set(self.context.updatedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were updated in the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction.
*/
public func updatedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access updated object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access updated object IDs from an already committed \(typeName(self))."
)
return Set(self.context.updatedObjects.flatMap { $0 as? T }.map { $0.objectID })
}
/**
Returns all pending `NSManagedObject`s that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObject`s that were deleted from the transaction.
*/
public func deletedObjects() -> Set<NSManagedObject> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access deleted objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access deleted objects from an already committed \(typeName(self))."
)
return self.context.deletedObjects
}
/**
Returns all pending `NSManagedObject`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObject`s of the specified type that were deleted from the transaction.
*/
public func deletedObjects<T: NSManagedObject>(entity: T.Type) -> Set<T> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access deleted objects from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access deleted objects from an already committed \(typeName(self))."
)
return Set(self.context.deletedObjects.flatMap { $0 as? T })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
public func deletedObjectIDs() -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access deleted object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access deleted object IDs from an already committed \(typeName(self))."
)
return Set(self.context.deletedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
public func deletedObjectIDs<T: NSManagedObject>(entity: T.Type) -> Set<NSManagedObjectID> {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to access deleted object IDs from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to access deleted object IDs from an already committed \(typeName(self))."
)
return Set(self.context.deletedObjects.flatMap { $0 as? T }.map { $0.objectID })
}
// MARK: Internal
internal let context: NSManagedObjectContext
internal let transactionQueue: GCDQueue
internal let childTransactionQueue: GCDQueue = .createSerial("com.corestore.datastack.childtransactionqueue")
internal let supportsUndo: Bool
internal let bypassesQueueing: Bool
internal var isCommitted = false
internal var result: SaveResult?
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool, bypassesQueueing: Bool) {
let context = mainContext.temporaryContextInTransactionWithConcurrencyType(
queue == .Main
? .MainQueueConcurrencyType
: .PrivateQueueConcurrencyType
)
self.transactionQueue = queue
self.context = context
self.supportsUndo = supportsUndo
self.bypassesQueueing = bypassesQueueing
context.parentTransaction = self
if !supportsUndo {
context.undoManager = nil
}
else if context.undoManager == nil {
context.undoManager = NSUndoManager()
}
}
internal func isRunningInAllowedQueue() -> Bool {
return self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext()
}
}
|
mit
|
6c6ad15fb953e1f7917451a909d9cc5b
| 40.429461 | 415 | 0.645851 | 5.349317 | false | false | false | false |
austinzheng/swift
|
test/IRGen/associated_types.swift
|
4
|
4628
|
// RUN: %target-swift-frontend -emit-ir -primary-file %s | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=i386 || CPU=x86_64
protocol Runcer {
associatedtype Runcee
}
protocol Runcible {
associatedtype RuncerType : Runcer
associatedtype AltRuncerType : Runcer
}
struct Mince {}
struct Quince : Runcer {
typealias Runcee = Mince
}
struct Spoon : Runcible {
typealias RuncerType = Quince
typealias AltRuncerType = Quince
}
struct Owl<T : Runcible, U> {
// CHECK: define hidden swiftcc void @"$s16associated_types3OwlV3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque*
func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { }
}
class Pussycat<T : Runcible, U> {
init() {}
// CHECK: define hidden swiftcc void @"$s16associated_types8PussycatC3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %T16associated_types8PussycatC* swiftself)
func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { }
}
func owl() -> Owl<Spoon, Int> {
return Owl()
}
func owl2() {
Owl<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon())
}
func pussycat() -> Pussycat<Spoon, Int> {
return Pussycat()
}
func pussycat2() {
Pussycat<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon())
}
protocol Speedy {
static func accelerate()
}
protocol FastRuncer {
associatedtype Runcee : Speedy
}
protocol FastRuncible {
associatedtype RuncerType : FastRuncer
}
// This is a complex example demonstrating the need to pull conformance
// information for archetypes from all paths to that archetype, not just
// its parent relationships.
func testFastRuncible<T: Runcible, U: FastRuncible>(_ t: T, u: U)
where T.RuncerType == U.RuncerType {
U.RuncerType.Runcee.accelerate()
}
// CHECK: define hidden swiftcc void @"$s16associated_types16testFastRuncible_1uyx_q_tAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) #0 {
// 1. Get the type metadata for U.RuncerType.Runcee.
// 1a. Get the type metadata for U.RuncerType.
// Note that we actually look things up in T, which is going to prove unfortunate.
// CHECK: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %T.Runcible, %swift.type* %T, %swift.protocol_requirement* getelementptr{{.*}}i32 12), i32 -1), %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types8RuncibleMp", i32 0, i32 14)) [[NOUNWIND_READNONE:#.*]]
// CHECK-NEXT: %T.RuncerType = extractvalue %swift.metadata_response [[T2]], 0
// CHECK-NEXT: store %swift.type*
// 2. Get the witness table for U.RuncerType.Runcee : Speedy
// 2a. Get the protocol witness table for U.RuncerType : FastRuncer.
// CHECK-NEXT: %T.RuncerType.FastRuncer = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %U.FastRuncible, %swift.type* %U, %swift.type* %T.RuncerType
// 1c. Get the type metadata for U.RuncerType.Runcee.
// CHECK-NEXT: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, {{.*}}, %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types10FastRuncerMp", i32 0, i32 10))
// CHECK-NEXT: %T.RuncerType.Runcee = extractvalue %swift.metadata_response [[T2]], 0
// CHECK-NEXT: store %swift.type*
// 2b. Get the witness table for U.RuncerType.Runcee : Speedy.
// CHECK-NEXT: %T.RuncerType.Runcee.Speedy = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, %swift.type* %T.RuncerType.Runcee
// 3. Perform the actual call.
// CHECK-NEXT: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.Runcee.Speedy, i32 1
// CHECK-NEXT: [[T0:%.*]] = load i8*, i8** [[T0_GEP]]
// CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to void (%swift.type*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[T1]](%swift.type* swiftself %T.RuncerType.Runcee, %swift.type* %T.RuncerType.Runcee, i8** %T.RuncerType.Runcee.Speedy)
public protocol P0 {
associatedtype ErrorType : Swift.Error
}
public struct P0Impl : P0 {
public typealias ErrorType = Swift.Error
}
// CHECK: define{{.*}} swiftcc i8** @"$s16associated_types6P0ImplVAA0C0AA9ErrorTypeAaDP_s0E0PWT"(%swift.type* %P0Impl.ErrorType, %swift.type* %P0Impl, i8** %P0Impl.P0)
// CHECK: ret i8** @"$ss5ErrorWS"
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
|
apache-2.0
|
d9ef588f3e8749b03706218859cff716
| 41.851852 | 355 | 0.69879 | 3.343931 | false | false | false | false |
svanimpe/around-the-table
|
Sources/AroundTheTable/Models/BSONExtensions.swift
|
1
|
2027
|
import BSON
import Foundation
/**
Adds `BSON.Primitive` conformance to `ClosedRange`.
*/
extension ClosedRange: Primitive where Bound: Primitive {
/// A `ClosedRange` is stored as a BSON `Document`.
public var typeIdentifier: Byte {
return Document().typeIdentifier
}
/// This `ClosedRange` as a BSON `Document`.
var document: Document {
return [
"lowerBound": lowerBound,
"upperBound": upperBound
]
}
/**
Returns this `ClosedRange` as a BSON `Document` in binary form.
*/
public func makeBinary() -> Bytes {
return document.makeBinary()
}
/**
Decodes a `ClosedRange` from a BSON primitive.
- Returns: `nil` when the primitive is not a `Document`.
- Throws: a `BSONError` when the document does not contain all required properties.
*/
init?(_ bson: Primitive?) throws {
guard let bson = bson as? Document else {
return nil
}
guard let lowerBound = bson["lowerBound"] as? Bound else {
throw log(BSONError.missingField(name: "lowerBound"))
}
guard let upperBound = bson["upperBound"] as? Bound else {
throw log(BSONError.missingField(name: "upperBound"))
}
self = lowerBound...upperBound
}
}
/**
Adds `BSON.Primitive` conformance to `URL`.
*/
extension URL: Primitive {
/// A `URL` is stored as a string.
public var typeIdentifier: Byte {
return absoluteString.typeIdentifier
}
/**
Returns this `URL` as a string in binary form.
*/
public func makeBinary() -> Bytes {
return absoluteString.makeBinary()
}
/**
Decodes a `URL` from a BSON primitive.
- Returns: `nil` when the primitive is not a string.
*/
init?(_ bson: Primitive?) throws {
guard let absoluteString = String(bson) else {
return nil
}
self.init(string: absoluteString)
}
}
|
bsd-2-clause
|
3baa159ec7cf30861693140ce3a2846c
| 25.324675 | 88 | 0.586088 | 4.596372 | false | true | false | false |
williamcaruso/OverTap
|
OverTap/ShapesViewController.swift
|
1
|
20062
|
//
// ShapesViewController.swift
// OverTap
//
// Created by William Caruso on 11/22/16.
// Copyright © 2016 wcaruso. All rights reserved.
//
import UIKit
import RSClipperWrapper
import KCFloatingActionButton
class ShapesViewController: UIViewController, UIGestureRecognizerDelegate {
// MARK: - Variables
var layersToRemove = [String: CAShapeLayer]()
var pointsInView = [UIView: Array<CGPoint>]()
var shapesInView = [UIView: CAShapeLayer]()
var shapeIdInView = [UIView: Int]()
var VIEW_IDS = [UIView: String]()
let NUM_SHAPES = 6
let VIEW_HASHES = ["view1view2", "view1view3", "view2view3"]
let redColor = UIColor(colorLiteralRed: 0.733, green: 0.027, blue: 0.067, alpha: 1.00)
let orangeColor = UIColor(colorLiteralRed: 0.992, green: 0.553, blue: 0.180, alpha: 1.00)
let yellowColor = UIColor(colorLiteralRed: 0.843, green: 0.992, blue: 0.208, alpha: 1.00)
let greenColor = UIColor(colorLiteralRed: 0.061, green: 0.984, blue: 0.100, alpha: 1.00)
let blueColor = UIColor(colorLiteralRed: 0.141, green: 0.043, blue: 0.824, alpha: 1.00)
let purpleColor = UIColor(colorLiteralRed: 0.584, green: 0.145, blue: 0.984, alpha: 1.00)
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBOutlet weak var view3: UIView!
@IBOutlet var view1RotationGestureRecognizer: UIRotationGestureRecognizer!
@IBOutlet var view2RotationGestureRecognizer: UIRotationGestureRecognizer!
@IBOutlet var view3RotationGestureRecognizer: UIRotationGestureRecognizer!
// MARK: - View Controllers
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
headerLabel.isHidden = true
view1.backgroundColor = UIColor.clear
view2.backgroundColor = UIColor.clear
view3.backgroundColor = UIColor.clear
view1.alpha = 0.6
view2.alpha = 0.6
view3.alpha = 0.6
VIEW_IDS = [view1: "view1", view2: "view2", view3: "view3"]
// setup tap gesture recognizers
let recognizer1 = UITapGestureRecognizer(target: self, action:#selector(handleTap(_:)))
recognizer1.delegate = self
view1.addGestureRecognizer(recognizer1)
let recognizer2 = UITapGestureRecognizer(target: self, action:#selector(handleTap(_:)))
recognizer2.delegate = self
view2.addGestureRecognizer(recognizer2)
let recognizer3 = UITapGestureRecognizer(target: self, action:#selector(handleTap(_:)))
recognizer3.delegate = self
view3.addGestureRecognizer(recognizer3)
// draw a square in each view
drawShape(drawInView: view1, shapeId: 1, color: redColor)
drawShape(drawInView: view2, shapeId: 1, color: blueColor)
drawShape(drawInView: view3, shapeId: 1, color: greenColor)
view3.isHidden = true
// add the floating action button
let fab = KCFloatingActionButton()
fab.addItem("Credits", icon: UIImage(named: "credits.png")!, handler: { item in
self.performSegue(withIdentifier: "Credits", sender: nil)
fab.close()
})
fab.addItem("Remove Third Shape", icon: UIImage(named: "delete.jpg")!, handler: { item in
self.view3.isHidden = true
self.findIntersections()
fab.close()
})
fab.addItem("Add Third Shape", icon: UIImage(named: "shapes.png")!, handler: { item in
self.view3.isHidden = false
self.findIntersections()
fab.close()
})
self.view.addSubview(fab)
}
// MARK: - Gesture Handlers
func gestureRecognizer(_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
return true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
if touch.force == touch.maximumPossibleForce {
let loc:CGPoint = touch.location(in: self.view)
for view in view.subviews {
if view.frame.contains(loc) {
showActionMenu(subview: view)
break
}
}
}
}
}
func handleTap(_ recognizer:UITapGestureRecognizer) {
if let view = recognizer.view {
let shape = shapesInView[view]!
switch shape.fillColor! {
case redColor.cgColor:
shape.fillColor = orangeColor.cgColor
case orangeColor.cgColor:
shape.fillColor = yellowColor.cgColor
case yellowColor.cgColor:
shape.fillColor = greenColor.cgColor
case greenColor.cgColor:
shape.fillColor = blueColor.cgColor
case blueColor.cgColor:
shape.fillColor = purpleColor.cgColor
default:
shape.fillColor = redColor.cgColor
}
}
findIntersections()
}
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint(), in: self.view)
if recognizer.state == UIGestureRecognizerState.ended {
let velocity = recognizer.velocity(in: self.view)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
let slideMultiplier = magnitude / 200
let slideFactor = 0.1 * slideMultiplier //Increase for more of a slide
var finalPoint = CGPoint(x:recognizer.view!.center.x + (velocity.x * slideFactor),
y:recognizer.view!.center.y + (velocity.y * slideFactor))
finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width)
finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height)
UIView.animate(withDuration: Double(slideFactor * 2),
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: {recognizer.view!.center = finalPoint },
completion: nil)
}
findIntersections()
}
@IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
recognizer.scale = 1
pointsInView[view] = getShapePoints(subview: view)
}
findIntersections()
}
@IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
pointsInView[view] = getShapePoints(subview: view)
}
findIntersections()
}
// MARK: - Methods
/**
Changes the shape in a view
- parameter subview: The view to change the shape in.
- parameter newShape: The shape to draw in the view
- return The coordinates of the shape.
*/
func changeShape(subview: UIView, newShape: Int) {
let oldShape = shapesInView[subview]
let col = UIColor(cgColor: (oldShape?.fillColor!)!)
// remove old shape from subview
oldShape?.removeFromSuperlayer()
drawShape(drawInView: subview, shapeId: newShape, color: col)
findIntersections()
}
/**
Caclulates points of the shape in the subview
- parameter subview: The view thta the shape is in.
- return The coordinates of the shape.
*/
func getShapePoints( subview: UIView ) -> Array<CGPoint> {
var points:Array<CGPoint> = []
let o = CGPoint(x: 0, y: 0)
let height = subview.frame.height
let width = subview.frame.width
switch shapeIdInView[subview]! {
case 0: //Triangle
points = [CGPoint(x: o.x,y: o.y),
CGPoint(x: o.x + width,y: o.y),
CGPoint(x: o.x + width,y: o.y + height)]
case 1: // Square
points = [CGPoint(x: o.x,y: o.y),
CGPoint(x: o.x + width,y: o.y),
CGPoint(x: o.x + width,y: o.y + height),
CGPoint(x: o.x ,y: o.y + height)]
case 2: // Rectangle
points = [CGPoint(x: o.x,y: o.y),
CGPoint(x: o.x + width / 2.0,y: o.y),
CGPoint(x: o.x + width / 2.0,y: o.y + height),
CGPoint(x: o.x ,y: o.y + height)]
case 3: // Pentagon
points = [CGPoint(x: o.x + width / 2.0,y: o.y),
CGPoint(x: o.x + width,y: o.y + 2 * height / 5.0),
CGPoint(x: o.x + 4 * width / 5,y: o.y + height),
CGPoint(x: o.x + width / 5.0,y: o.y + height),
CGPoint(x: o.x,y: o.y + 2.0 * height / 5.0)]
case 4: // Hexagon
points = [CGPoint(x: o.x + width / 4.0,y: o.y + height / 16.0),
CGPoint(x: o.x + 3 * width / 4.0,y: o.y + height / 16.0),
CGPoint(x: o.x + width,y: o.y + 8 * height / 16.0),
CGPoint(x: o.x + 3 * width / 4.0,y: o.y + 15 * height / 16.0),
CGPoint(x: o.x + width / 4.0,y: o.y + 15 * height / 16.0),
CGPoint(x: o.x,y: o.y + 8 * height / 16.0)]
case 5: // Octagon
points = [CGPoint(x: o.x + width / 3.0,y: o.y),
CGPoint(x: o.x + 2 * width / 3.0,y: o.y),
CGPoint(x: o.x + width,y: o.y + height / 3.0),
CGPoint(x: o.x + width,y: o.y + 2 * height / 3.0),
CGPoint(x: o.x + 2 * width / 3.0,y: o.y + height),
CGPoint(x: o.x + width / 3.0,y: o.y + height),
CGPoint(x: o.x,y: o.y + 2 * height / 3.0),
CGPoint(x: o.x,y: o.y + height / 3.0)]
default:
points = []
}
return points
}
/**
Draws a shape inside of a view and adds a sublayer
- parameter drawInView: The view to draw in.
- parameter shape: The shape to draw.
*/
func drawShape( drawInView: UIView, shapeId: Int, color: UIColor) {
shapeIdInView[drawInView] = shapeId
var points:Array<CGPoint> = getShapePoints(subview: drawInView)
let shape = CAShapeLayer()
drawInView.layer.addSublayer(shape)
shape.opacity = 0.8
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = color.cgColor
let firstPoint = points[0]
let path = UIBezierPath()
path.move(to: firstPoint)
var polygonIterator = points.makeIterator()
while let point = polygonIterator.next() {
path.addLine(to: point)
}
path.close()
shape.path = path.cgPath
pointsInView[drawInView] = points
shapesInView[drawInView] = shape
}
/**
Rotates a point by a certain amount of radians around an origin
- parameter target: The point to rotate.
- parameter aroundOrigin: The origin to rotate about.
- parameter byRadians: The angle of rotation (radians).
- return The transformed point.
*/
func rotatePoint(target: CGPoint, origin: CGPoint, byRadians: CGFloat) -> CGPoint {
let dx = origin.x - target.x
let dy = origin.y - target.y
let a = abs(dx * sin(byRadians))
let b = abs(dx * cos(byRadians))
let radius = abs(sqrt(dx * dx + dy * dy) / (a + b) * dx)
let alpha = atan2(dy, dx) // in radians
let newAlpha = alpha + byRadians
let x = origin.x + radius * cos(newAlpha)
let y = origin.y + radius * sin(newAlpha)
return CGPoint(x: x, y: y)
}
/**
Transforms a subviews points to the coordinate frame of the superview
- parameter subview: The view whose points to transform.
- return The transformed points.
*/
func transformPointsToSuperview( subview: UIView ) -> Array<CGPoint> {
let points = pointsInView[subview]!
var transPoints = Array<CGPoint>()
let origin = subview.frame.origin
var transPoint = CGPoint()
let refPoint = CGPoint(x: origin.x + (subview.frame.width / 2.0),y: origin.y + (subview.frame.height / 2.0))
for point in points {
transPoint = CGPoint(x: point.x + origin.x, y: point.y + origin.y)
if (subview.transform.b != 0) { // rotation
let radians = CGFloat(atan2f(Float(subview.transform.b), Float(subview.transform.a)))
let rotatedPoint = rotatePoint(target: transPoint, origin: refPoint, byRadians: radians)
transPoints.append(rotatedPoint)
} else {
transPoints.append(transPoint)
}
}
return transPoints
}
/**
Blends two UIColors together
- parameter color1: The first UIolor.
- parameter color2: The second UIolor.
- return The blended UIColor.
*/
func blendColor(color1: UIColor, withColor color2: UIColor) -> UIColor {
var r1:CGFloat = 0, g1:CGFloat = 0, b1:CGFloat = 0, a1:CGFloat = 0
var r2:CGFloat = 0, g2:CGFloat = 0, b2:CGFloat = 0, a2:CGFloat = 0
color1.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
color2.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
return UIColor(red: max(r1, r2), green: max(g1, g2), blue: max(b1, b2), alpha: max(a1, a2))
}
/**
Finds the intersections of the non-hidden UIViews and then draws them
*/
func findIntersections() {
// first remove the old shapes
for hash in VIEW_HASHES {
if (layersToRemove[hash]?.superlayer != nil) {
layersToRemove[hash]?.removeFromSuperlayer()
}
}
var intersections = [(UIView, UIView)]()
if (!view1.isHidden && !view2.isHidden && !view3.isHidden) {
if view1.frame.intersects(view2.frame) { intersections.append((view1, view2)) }
if view1.frame.intersects(view3.frame) { intersections.append((view1, view3)) }
if view2.frame.intersects(view3.frame) { intersections.append((view2, view3)) }
} else if (!view1.isHidden && !view2.isHidden) {
if view1.frame.intersects(view2.frame) { intersections.append((view1, view2)) }
} else {
// no intersections
headerLabel.isHidden = true
}
if intersections.count == 0 {
headerLabel.isHidden = true
} else {
for pair in intersections {
drawIntersection(pair: pair)
}
}
}
/**
Draw the intersection of the polgyons
*/
func drawIntersection(pair : (UIView, UIView)) {
let viewA = pair.0
let viewB = pair.1
let hash = VIEW_IDS[viewA]! + VIEW_IDS[viewB]!
// get transform points
let points1 = transformPointsToSuperview(subview: viewA)
let points2 = transformPointsToSuperview(subview: viewB)
let intersection = Clipper.intersectPolygons([points2], withPolygons: [points1])
// draw the intersection
let shape = CAShapeLayer()
view.layer.addSublayer(shape)
shape.opacity = 0.6
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor.white.cgColor
shape.fillColor = blendColor(color1: UIColor(cgColor: (shapesInView[viewA]?.fillColor)!), withColor: UIColor(cgColor: (shapesInView[viewB]?.fillColor)!)).cgColor
if (layersToRemove[hash] != shape) {
// haptic feedback becasue a new intersection is being made
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
// remove the old sublayer
if (layersToRemove[hash]?.superlayer != nil) {
layersToRemove[hash]?.removeFromSuperlayer()
}
layersToRemove[hash] = shape
var intersectionIterator = intersection.makeIterator()
while let polygon = intersectionIterator.next() {
let firstPoint = polygon[0]
let path = UIBezierPath()
path.move(to: CGPoint(x: firstPoint.x,y: firstPoint.y))
var polygonIterator = polygon.makeIterator()
while let point = polygonIterator.next() {
path.addLine(to: CGPoint(x: point.x,y: point.y))
}
path.close()
shape.path = path.cgPath
headerLabel.isHidden = false
}
}
}
/**
Displays an action menu to change a view's shape
-parameter subview: The subview whose shape to change
*/
func showActionMenu(subview: UIView) {
let optionMenu = UIAlertController(title: nil, message: "Choose Shape", preferredStyle: .actionSheet)
let triangleAction = UIAlertAction(title: "Triangle", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 0)
})
let squareAction = UIAlertAction(title: "Square", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 1)
})
let rectangleAction = UIAlertAction(title: "Rectangle", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 2)
})
let pentagonAction = UIAlertAction(title: "Pentagon", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 3)
})
let hexagonAction = UIAlertAction(title: "Hexagon", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 4)
})
let octagonAction = UIAlertAction(title: "Octagon", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.changeShape(subview: subview, newShape: 5)
})
let dismissAction = UIAlertAction(title: "Dismiss", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
})
optionMenu.addAction(triangleAction)
optionMenu.addAction(squareAction)
optionMenu.addAction(rectangleAction)
optionMenu.addAction(pentagonAction)
optionMenu.addAction(hexagonAction)
optionMenu.addAction(octagonAction)
optionMenu.addAction(dismissAction)
self.present(optionMenu, animated: true, completion: nil)
}
}
|
mit
|
a5cf9e1fd95d00cb335da8f2c72e2047
| 37.431034 | 169 | 0.562285 | 4.390676 | false | false | false | false |
elpassion/el-space-ios
|
ELSpace/Commons/Loading/LoadingIndicator.swift
|
1
|
1157
|
import UIKit
import MBProgressHUD
import RxSwift
class LoadingIndicator {
init(superView: UIView) {
self.superView = superView
}
deinit {
hud?.hide(animated: true)
}
func loading(_ loading: Bool) {
if loading {
operationsCount += 1
} else if operationsCount >= 1 {
operationsCount -= 1
}
}
// MARK: - Private
private let superView: UIView
private weak var hud: MBProgressHUD?
private var operationsCount: UInt = 0 {
didSet {
updateHud()
}
}
private func updateHud() {
if operationsCount > 0 && hud == nil {
hud = MBProgressHUD.showAdded(to: superView, animated: true)
} else if operationsCount <= 0 {
hud?.hide(animated: true)
}
}
}
extension LoadingIndicator: ReactiveCompatible {}
extension Reactive where Base: LoadingIndicator {
var isLoading: AnyObserver<Bool> {
return AnyObserver(eventHandler: { [weak base] event in
guard let element = event.element else { return }
base?.loading(element)
})
}
}
|
gpl-3.0
|
2184646e096639bc1cd603a901c8e748
| 20.036364 | 72 | 0.579084 | 4.703252 | false | false | false | false |
Johnykutty/SwiftLint
|
Source/SwiftLintFramework/Rules/LargeTupleRule.swift
|
1
|
7717
|
//
// LargeTupleRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 01/01/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
private enum LargeTupleRuleError: Error {
case unbalencedParentheses
}
public struct LargeTupleRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 2, error: 3)
public init() {}
public static let description = RuleDescription(
identifier: "large_tuple",
name: "Large Tuple",
description: "Tuples shouldn't have too many members. Create a custom type instead.",
nonTriggeringExamples: [
"let foo: (Int, Int)\n",
"let foo: (start: Int, end: Int)\n",
"let foo: (Int, (Int, String))\n",
"func foo() -> (Int, Int)\n",
"func foo() -> (Int, Int) {}\n",
"func foo(bar: String) -> (Int, Int)\n",
"func foo(bar: String) -> (Int, Int) {}\n",
"func foo() throws -> (Int, Int)\n",
"func foo() throws -> (Int, Int) {}\n",
"let foo: (Int, Int, Int) -> Void\n",
"var completionHandler: ((_ data: Data?, _ resp: URLResponse?, _ e: NSError?) -> Void)!"
],
triggeringExamples: [
"↓let foo: (Int, Int, Int)\n",
"↓let foo: (start: Int, end: Int, value: String)\n",
"↓let foo: (Int, (Int, Int, Int))\n",
"func foo(↓bar: (Int, Int, Int))\n",
"func foo() -> ↓(Int, Int, Int)\n",
"func foo() -> ↓(Int, Int, Int) {}\n",
"func foo(bar: String) -> ↓(Int, Int, Int)\n",
"func foo(bar: String) -> ↓(Int, Int, Int) {}\n",
"func foo() throws -> ↓(Int, Int, Int)\n",
"func foo() throws -> ↓(Int, Int, Int) {}\n",
"func foo() throws -> ↓(Int, ↓(String, String, String), Int) {}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let offsets = violationOffsetsForTypes(in: file, dictionary: dictionary, kind: kind) +
violationOffsetsForFunctions(in: file, dictionary: dictionary, kind: kind)
return offsets.flatMap { location, size in
for parameter in configuration.params where size > parameter.value {
let reason = "Tuples should have at most \(parameter.value) members."
return StyleViolation(ruleDescription: type(of: self).description,
severity: parameter.severity,
location: Location(file: file, byteOffset: location),
reason: reason)
}
return nil
}
}
private func violationOffsetsForTypes(in file: File, dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> [(offset: Int, size: Int)] {
let kinds = SwiftDeclarationKind.variableKinds().filter { $0 != .varLocal }
guard kinds.contains(kind),
let type = dictionary.typeName,
let offset = dictionary.offset,
let ranges = try? parenthesesRanges(in: type) else {
return []
}
var text = type.bridge()
var maxSize: Int?
for range in ranges {
let substring = text.substring(with: range)
if !containsReturnArrow(in: text.bridge(), range: range) {
let size = substring.components(separatedBy: ",").count
maxSize = max(size, maxSize ?? .min)
}
let replacement = String(repeating: " ", count: substring.bridge().length)
text = text.replacingCharacters(in: range, with: replacement).bridge()
}
return maxSize.flatMap { [(offset: offset, size: $0)] } ?? []
}
private func violationOffsetsForFunctions(in file: File, dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> [(offset: Int, size: Int)] {
let contents = file.contents.bridge()
guard SwiftDeclarationKind.functionKinds().contains(kind),
let returnRange = returnRangeForFunction(dictionary: dictionary),
let returnSubstring = contents.substringWithByteRange(start: returnRange.location,
length: returnRange.length),
let ranges = try? parenthesesRanges(in: returnSubstring) else {
return []
}
var text = returnSubstring.bridge()
var offsets = [(offset: Int, size: Int)]()
for range in ranges {
let substring = text.substring(with: range)
if let byteRange = text.NSRangeToByteRange(start: range.location, length: range.length),
!containsReturnArrow(in: text.bridge(), range: range) {
let size = substring.components(separatedBy: ",").count
let offset = byteRange.location + returnRange.location
offsets.append((offset: offset, size: size))
}
let replacement = String(repeating: " ", count: substring.bridge().length)
text = text.replacingCharacters(in: range, with: replacement).bridge()
}
return offsets.sorted(by: { $0.offset < $1.offset })
}
private func returnRangeForFunction(dictionary: [String: SourceKitRepresentable]) -> NSRange? {
guard let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let length = dictionary.length,
let offset = dictionary.offset else {
return nil
}
let start = nameOffset + nameLength
let end = dictionary.bodyOffset ?? length + offset
guard end - start > 0 else {
return nil
}
return NSRange(location: start, length: end - start)
}
private func parenthesesRanges(in text: String) throws -> [NSRange] {
var stack = [Int]()
var balanced = true
var ranges = [NSRange]()
let nsText = text.bridge()
let parentheses = CharacterSet(charactersIn: "()")
var index = 0
let length = nsText.length
while balanced {
let searchRange = NSRange(location: index, length: length - index)
let range = nsText.rangeOfCharacter(from: parentheses, options: [], range: searchRange)
if range.location == NSNotFound {
break
}
index = NSMaxRange(range)
let symbol = nsText.substring(with: range)
if symbol == "(" {
stack.append(range.location)
} else if let startIdx = stack.popLast() {
ranges.append(NSRange(location: startIdx, length: range.location - startIdx + 1))
} else {
balanced = false
}
}
guard balanced && stack.isEmpty else {
throw LargeTupleRuleError.unbalencedParentheses
}
return ranges
}
private func containsReturnArrow(in text: String, range: NSRange) -> Bool {
let arrowRegex = regex("\\s*->")
let start = NSMaxRange(range)
let restOfStringRange = NSRange(location: start, length: text.bridge().length - start)
guard let match = arrowRegex.firstMatch(in: text, options: [], range: restOfStringRange)?.range else {
return false
}
return match.location == start
}
}
|
mit
|
799c8e8b059fd9341df5747f325e9ce8
| 38.446154 | 110 | 0.558762 | 4.678832 | false | false | false | false |
idea4good/GuiLiteSamples
|
Hello3D/BuildAppleWatch/Hello3D WatchKit Extension/GuiLiteImage.swift
|
1
|
2083
|
import UIKit
class GuiLiteImage {
let width, height, colorBytes : Int
let buffer: UnsafeMutableRawPointer
init(width: Int, height: Int, colorBytes: Int) {
self.width = width
self.height = height
self.colorBytes = colorBytes
self.buffer = malloc(width * height * 4)
}
func getUiImage() -> CGImage?{
let pixData = (colorBytes == 2) ? getPixelsFrom16bits() : getPixelsFrom32bits()
if(pixData == nil){
return nil
}
let providerRef = CGDataProvider(data: pixData!)
let bitmapInfo:CGBitmapInfo = [.byteOrder32Little, CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue)]
return CGImage(width: Int(width), height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
}
func getPixelsFrom16bits()->CFData?{
let rawData = getUiOfHello3D(nil, nil, false)
if rawData == nil{
return nil
}
for index in 0..<width * height {
let rgb16 = rawData?.load(fromByteOffset: index * 2, as: UInt16.self)
let rgb32 = UInt32(rgb16!)
let color = ((rgb32 & 0xF800) << 8 | ((rgb32 & 0x7E0) << 5) | ((rgb32 & 0x1F) << 3))
buffer.storeBytes(of: color, toByteOffset: index * 4, as: UInt32.self)
}
let rawPointer = UnsafeRawPointer(buffer)
let pixData: UnsafePointer = rawPointer.assumingMemoryBound(to: UInt8.self)
return CFDataCreate(nil, pixData, width * height * 4)
}
func getPixelsFrom32bits()->CFData?{
let rawData = getUiOfHello3D(nil, nil, false)
if rawData == nil{
return nil
}
let rawPointer = UnsafeRawPointer(rawData)
let pixData: UnsafePointer = rawPointer!.assumingMemoryBound(to: UInt8.self)
return CFDataCreate(nil, pixData, width * height * 4)
}
}
|
apache-2.0
|
3a5f70622f95138127cda1d859644c38
| 38.301887 | 268 | 0.614978 | 4.312629 | false | false | false | false |
snowpunch/AppLove
|
App Love/Network/SearchApps.swift
|
1
|
1343
|
//
// SearchApps.swift
// App Love
//
// Created by Woodie Dovich on 2016-03-26.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Loads array of suggested [AppModel] for search terms.
//
import Alamofire
import SwiftyJSON
class SearchApps {
class func get(searchStr:String, completion: (appsFound:[AppModel]?,succeeded: Bool, error:NSError?) -> Void) {
let array = searchStr.characters.split {$0 == " "}.map(String.init)
let searchTermsStr = array.joinWithSeparator("+").lowercaseString
let url = "https://itunes.apple.com/search?term=\(searchTermsStr)&entity=software"
Alamofire.request(.GET, url).responseJSON { response in
switch response.result {
case .Success(let data):
var apps = [AppModel]()
if let resultsArray = data["results"] as? [AnyObject] {
for resultsDic in resultsArray {
let app = AppModel(resultsDic: resultsDic as! [String : AnyObject])
apps.append(app)
}
}
completion(appsFound: apps, succeeded: true , error: nil)
case .Failure(let error):
completion(appsFound: nil, succeeded: false , error: error)
}
}
}
}
|
mit
|
379026b9c6dd2ba76986fbc660a25ee6
| 34.315789 | 115 | 0.568554 | 4.473333 | false | false | false | false |
swordfishyou/fieldstool
|
FieldTool/Sources/Models/CoordinatesCollection.swift
|
1
|
1071
|
//
// CoordinatesCollection.swift
// FieldTool
//
import CoreLocation
protocol CoordinatesCollection {
var coordinates: [CLLocationCoordinate2D] { get set }
}
struct CoordinatesContainer: CoordinatesCollection {
var coordinates: [CLLocationCoordinate2D]
}
extension CoordinatesContainer {
public var hashValue: Int {
let prime = 31
var result = 1
self.coordinates.forEach {
result = prime * result + $0.hashValue
}
return result
}
public static func == (lhs: CoordinatesContainer, rhs: CoordinatesContainer) -> Bool {
return lhs.coordinates == rhs.coordinates
}
}
extension CLLocationCoordinate2D: Hashable {
public var hashValue: Int {
return self.latitude.hashValue ^ self.longitude.hashValue
}
public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
let precision = 1e-15
return (lhs.latitude - rhs.latitude <= precision) && (lhs.longitude - rhs.longitude <= precision)
}
}
|
mit
|
4bff0ebfd6cdb4ce575b52d56ad2d90c
| 24.5 | 105 | 0.656396 | 4.656522 | false | false | false | false |
zvonicek/ImageSlideshow
|
Example/ImageSlideshow/TableViewController.swift
|
1
|
2524
|
//
// TableViewController.swift
// ImageSlideshow_Example
//
// Created by Petr Zvoníček on 25.02.18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import ImageSlideshow
struct Model {
let image: UIImage
let title: String
var inputSource: InputSource {
return ImageSource(image: image)
}
}
class TableViewController: UITableViewController {
let models = [Model(image: UIImage(named: "img1")!, title: "First image"), Model(image: UIImage(named: "img2")!, title: "Second image"), Model(image: UIImage(named: "img3")!, title: "Third image"), Model(image: UIImage(named: "img4")!, title: "Fourth image")]
var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate? = nil
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let model = models[indexPath.row]
cell.imageView?.image = model.image
cell.textLabel?.text = model.title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let fullScreenController = FullScreenSlideshowViewController()
fullScreenController.inputs = models.map { $0.inputSource }
fullScreenController.initialPage = indexPath.row
if let cell = tableView.cellForRow(at: indexPath), let imageView = cell.imageView {
slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(imageView: imageView, slideshowController: fullScreenController)
fullScreenController.modalPresentationStyle = .custom
fullScreenController.transitioningDelegate = slideshowTransitioningDelegate
}
fullScreenController.slideshow.currentPageChanged = { [weak self] page in
if let cell = tableView.cellForRow(at: IndexPath(row: page, section: 0)), let imageView = cell.imageView {
self?.slideshowTransitioningDelegate?.referenceImageView = imageView
}
}
present(fullScreenController, animated: true, completion: nil)
}
}
|
mit
|
6a04ecd68e20d88ee9ab59575d695c96
| 36.626866 | 263 | 0.702499 | 5.052104 | false | false | false | false |
bboyfeiyu/MaterialKit
|
Example/MaterialKit/TextFieldViewController.swift
|
1
|
2871
|
//
// TextFieldViewController.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/15/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class TextFieldViewController: UIViewController {
@IBOutlet var textField1: MKTextField!
@IBOutlet var textField2: MKTextField!
@IBOutlet var textField3: MKTextField!
@IBOutlet var textField4: MKTextField!
@IBOutlet var textField5: MKTextField!
@IBOutlet var textField6: MKTextField!
override func viewDidLoad() {
// No border, no shadow, floatPlaceHolderDisabled
textField1.layer.borderColor = UIColor.clearColor().CGColor
textField1.placeholder = "Placeholder"
textField1.tintColor = UIColor.grayColor()
// No border, shadow, floatPlaceHolderDisabled
textField2.layer.borderColor = UIColor.clearColor().CGColor
textField2.placeholder = "Repo name"
textField2.backgroundColor = UIColor(hex: 0xE0E0E0)
textField2.tintColor = UIColor.grayColor()
/*
textField2.layer.shadowOpacity = 1.0
textField2.layer.shadowRadius = 1.5
textField2.layer.shadowColor = UIColor.MKColor.Red.CGColor
textField2.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
textField2.borderStyle = .None
*/
// Border, no shadow, floatPlaceHolderDisabled
textField3.layer.borderColor = UIColor.MKColor.Grey.CGColor
textField3.circleLayerColor = UIColor.MKColor.Amber
textField3.tintColor = UIColor.MKColor.DeepOrange
textField3.rippleLocation = .Left
// No border, no shadow, floatingPlaceholderEnabled
textField4.layer.borderColor = UIColor.clearColor().CGColor
textField4.floatingPlaceholderEnabled = true
textField4.placeholder = "Github"
textField4.tintColor = UIColor.MKColor.Blue
textField4.rippleLocation = .Right
// No border, shadow, floatingPlaceholderEnabled
textField5.layer.borderColor = UIColor.clearColor().CGColor
textField5.floatingPlaceholderEnabled = true
textField5.placeholder = "Email account"
textField5.circleLayerColor = UIColor.MKColor.LightBlue
textField5.tintColor = UIColor.MKColor.Blue
textField5.backgroundColor = UIColor(hex: 0xE0E0E0)
// Border, floatingPlaceholderEnabled
textField6.floatingPlaceholderEnabled = true
textField6.cornerRadius = 1.0
textField6.placeholder = "Description"
textField6.layer.borderColor = UIColor.MKColor.Green.CGColor
textField6.circleLayerColor = UIColor.MKColor.LightGreen
textField6.tintColor = UIColor.MKColor.LightGreen
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
}
|
mit
|
9bfab783c76ba069bceac6180de98a77
| 38.342466 | 74 | 0.691397 | 4.638126 | false | false | false | false |
vector-im/vector-ios
|
Riot/Modules/KeyVerification/Common/Verify/SAS/KeyVerificationVerifyBySASViewModel.swift
|
1
|
4495
|
// File created from ScreenTemplate
// $ createScreen.sh DeviceVerification/Verify DeviceVerificationVerify
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
final class KeyVerificationVerifyBySASViewModel: KeyVerificationVerifyBySASViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let transaction: MXSASTransaction
// MARK: Public
weak var viewDelegate: KeyVerificationVerifyBySASViewModelViewDelegate?
weak var coordinatorDelegate: KeyVerificationVerifyBySASViewModelCoordinatorDelegate?
let emojis: [MXEmojiRepresentation]?
let decimal: String?
let verificationKind: KeyVerificationKind
// MARK: - Setup
init(session: MXSession, transaction: MXSASTransaction, verificationKind: KeyVerificationKind) {
self.session = session
self.transaction = transaction
self.emojis = self.transaction.sasEmoji
self.decimal = self.transaction.sasDecimal
self.verificationKind = verificationKind
}
// MARK: - Public
func process(viewAction: KeyVerificationVerifyBySASViewAction) {
switch viewAction {
case .loadData:
self.registerTransactionDidStateChangeNotification(transaction: transaction)
case .confirm:
self.confirmTransaction()
case .complete:
self.coordinatorDelegate?.keyVerificationVerifyViewModelDidComplete(self)
case .cancel:
self.cancelTransaction()
self.coordinatorDelegate?.keyVerificationVerifyViewModelDidCancel(self)
}
}
// MARK: - Private
private func confirmTransaction() {
self.update(viewState: .loading)
self.transaction.confirmSASMatch()
}
private func cancelTransaction() {
self.transaction.cancel(with: MXTransactionCancelCode.user())
}
private func update(viewState: KeyVerificationVerifyViewState) {
self.viewDelegate?.keyVerificationVerifyBySASViewModel(self, didUpdateViewState: viewState)
}
// MARK: - MXKeyVerificationTransactionDidChange
private func registerTransactionDidStateChangeNotification(transaction: MXSASTransaction) {
NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: NSNotification.Name.MXKeyVerificationTransactionDidChange, object: transaction)
}
private func unregisterTransactionDidStateChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil)
}
@objc private func transactionDidStateChange(notification: Notification) {
guard let transaction = notification.object as? MXSASTransaction else {
return
}
switch transaction.state {
case MXSASTransactionStateVerified:
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .loaded)
self.coordinatorDelegate?.keyVerificationVerifyViewModelDidComplete(self)
case MXSASTransactionStateCancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(reason))
case MXSASTransactionStateError:
guard let error = transaction.error else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .error(error))
case MXSASTransactionStateCancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
}
|
apache-2.0
|
6e11f451d7084c304416f366449ee21f
| 35.544715 | 201 | 0.705451 | 5.953642 | false | false | false | false |
spweau/Test_DYZB
|
Test_DYZB/Test_DYZB/Classes/Tool/Common.swift
|
1
|
325
|
//
// Common.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/22.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH : CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
mit
|
8bdc6b86052475cdf3621224d9a0ac1d
| 15.1 | 46 | 0.701863 | 3.389474 | false | false | false | false |
trupin/Beaver
|
BeaverTestKit/Type/ActionMock.swift
|
2
|
331
|
import Beaver
public struct ActionMock: Action, Equatable {
public typealias StateType = StateMock
public var name: String
public init(name: String = "ActionMock") {
self.name = name
}
public static func ==(lhs: ActionMock, rhs: ActionMock) -> Bool {
return lhs.name == rhs.name
}
}
|
mit
|
e75262247db60105568df55030e1d04c
| 21.066667 | 69 | 0.63142 | 4.1375 | false | false | false | false |
mubstimor/smartcollaborationvapor
|
Sources/App/Controllers/SpecialistController.swift
|
1
|
3199
|
//
// SpecialistController.swift
// SmartCollaborationVapor
//
// Created by Timothy Mubiru on 28/02/2017.
//
//
import Vapor
import HTTP
import TurnstileCrypto
final class SpecialistController {
func addRoutes(drop: Droplet){
// let specialists = drop.grouped("specialists")
let specialists = drop.grouped(BasicAuthMiddleware(), StaticInfo.protect).grouped("api").grouped("specialists")
specialists.get(handler: index)
specialists.post(handler: create)
specialists.get(Specialist.self, handler: show)
specialists.patch(Specialist.self, handler: update)
specialists.get(Specialist.self, "treatments", handler: treatmentsIndex)
}
func index(request: Request) throws -> ResponseRepresentable {
return try Specialist.all().makeNode().converted(to: JSON.self)
}
func create(request: Request) throws -> ResponseRepresentable {
var specialist = try request.specialist()
try specialist.save()
return specialist
}
func show(request: Request, specialist: Specialist) throws -> ResponseRepresentable {
return specialist
}
func delete(request: Request, specialist: Specialist) throws -> ResponseRepresentable {
try specialist.delete()
return JSON([:])
}
func clear(request: Request) throws -> ResponseRepresentable {
try Specialist.query().delete()
return JSON([])
}
func update(request: Request, specialist: Specialist) throws -> ResponseRepresentable {
let new = try request.specialist()
var specialist = specialist
specialist.name = new.name
specialist.email = new.email
specialist.password = BCrypt.hash(password: new.password)
specialist.club_id = new.club_id
try specialist.save()
return specialist
}
func replace(request: Request, specialist: Specialist) throws -> ResponseRepresentable {
try specialist.delete()
return try create(request: request)
}
// func makeResource() -> Resource<Specialist> {
// return Resource(
// index: index,
// show: show,
// replace: replace,
// modify: update,
// destroy: delete,
// clear: clear
// )
// }
func treatmentsIndex(request: Request, specialist: Specialist) throws -> ResponseRepresentable {
let children = try specialist.treatments()
return try JSON(node: children.makeNode())
}
}
extension Request {
func specialist() throws -> Specialist {
guard let json = json else { throw Abort.badRequest }
return try Specialist(node: json)
}
}
extension Specialist: ResponseRepresentable {
func makeResponse() throws -> Response {
let json = try JSON(node:
[
"id": id,
"name": name,
"email": email.value,
"club_id": club_id,
"api_key_id": apiKeyID,
"api_key_secret": apiKeySecret
]
)
return try json.makeResponse()
}
}
|
mit
|
489cbc2b0c054a7ad02b2c52c3423686
| 28.897196 | 119 | 0.605814 | 4.480392 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/MonthSectionController.swift
|
2
|
4163
|
/**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class MonthSectionController: ListBindingSectionController<ListDiffable>, ListBindingSectionControllerDataSource, ListBindingSectionControllerSelectionDelegate {
private var selectedDay: Int = -1
override init() {
super.init()
dataSource = self
selectionDelegate = self
}
// MARK: ListBindingSectionControllerDataSource
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, viewModelsFor object: Any) -> [ListDiffable] {
guard let month = object as? Month else { return [] }
let date = Date()
let today = Calendar.current.component(.day, from: date)
var viewModels = [ListDiffable]()
viewModels.append(MonthTitleViewModel(name: month.name))
for day in 1..<(month.days + 1) {
let viewModel = DayViewModel(
day: day,
today: day == today,
selected: day == selectedDay,
appointments: month.appointments[day]?.count ?? 0
)
viewModels.append(viewModel)
}
for appointment in month.appointments[selectedDay] ?? [] {
viewModels.append(appointment)
}
return viewModels
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>,
cellForViewModel viewModel: Any,
at index: Int) -> UICollectionViewCell & ListBindable {
let cellClass: AnyClass
if viewModel is DayViewModel {
cellClass = CalendarDayCell.self
} else if viewModel is MonthTitleViewModel {
cellClass = MonthTitleCell.self
} else {
cellClass = LabelCell.self
}
guard let cell = collectionContext?.dequeueReusableCell(of: cellClass, for: self, at: index) as? UICollectionViewCell & ListBindable
else { fatalError() }
return cell
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>,
sizeForViewModel viewModel: Any,
at index: Int) -> CGSize {
guard let width = collectionContext?.containerSize.width else { return .zero }
if viewModel is DayViewModel {
let square = width / 7.0
return CGSize(width: square, height: square)
} else if viewModel is MonthTitleViewModel {
return CGSize(width: width, height: 30.0)
} else {
return CGSize(width: width, height: 55.0)
}
}
// MARK: ListBindingSectionControllerSelectionDelegate
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didSelectItemAt index: Int, viewModel: Any) {
guard let dayViewModel = viewModel as? DayViewModel else { return }
if dayViewModel.day == selectedDay {
selectedDay = -1
} else {
selectedDay = dayViewModel.day
}
update(animated: true)
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didDeselectItemAt index: Int, viewModel: Any) {}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didHighlightItemAt index: Int, viewModel: Any) {}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didUnhighlightItemAt index: Int, viewModel: Any) {}
}
|
apache-2.0
|
9847e95aa90421b5773762273ad9b520
| 38.647619 | 167 | 0.668028 | 5.463255 | false | false | false | false |
wdxgtsh/SwiftPasscodeLock
|
SwiftPasscodeLock/Views/PasscodeButton.swift
|
5
|
2763
|
//
// PasscodeButton.swift
// SwiftPasscodeLock
//
// Created by Yanko Dimitrov on 11/19/14.
// Copyright (c) 2014 Yanko Dimitrov. All rights reserved.
//
import UIKit
@IBDesignable
public class PasscodeButton: UIButton {
@IBInspectable
public var passcodeSign: String = "1"
@IBInspectable
public var borderWidth: CGFloat = 1 {
didSet {
setupView()
}
}
@IBInspectable
public var borderColor: UIColor = UIColor.whiteColor() {
didSet {
setupView()
}
}
@IBInspectable
public var borderRadius: CGFloat = 35 {
didSet {
setupView()
}
}
@IBInspectable
public var buttonBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
setupView()
}
}
@IBInspectable
public var buttonHighlightBackgroundColor: UIColor = UIColor.whiteColor() {
didSet {
setupView()
}
}
///////////////////////////////////////////////////////
// MARK: - Initializers
///////////////////////////////////////////////////////
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupActions()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupActions()
}
///////////////////////////////////////////////////////
// MARK: - Methods
///////////////////////////////////////////////////////
private func setupActions() {
addTarget(self, action: Selector("handleTouchDown"), forControlEvents: .TouchDown)
addTarget(self, action: Selector("handleTouchUp"), forControlEvents: .TouchUpInside | .TouchDragOutside | .TouchCancel)
}
private func setupView() {
layer.cornerRadius = borderRadius
layer.borderWidth = borderWidth
layer.borderColor = borderColor.CGColor
backgroundColor = buttonBackgroundColor
}
func handleTouchDown() {
animateButton(backgroundColor: buttonHighlightBackgroundColor)
}
func handleTouchUp() {
animateButton(backgroundColor: buttonBackgroundColor)
}
private func animateButton(#backgroundColor: UIColor) {
UIView.animateWithDuration(
0.3,
delay: 0.0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.0,
options: .AllowUserInteraction | .BeginFromCurrentState,
animations: {
self.backgroundColor = backgroundColor
},
completion: nil
)
}
}
|
mit
|
f0e87c89632bd40e929a89c181afda9e
| 23.026087 | 127 | 0.521173 | 6.099338 | false | false | false | false |
viWiD/Persist
|
Pods/Freddy/Sources/JSONParsing.swift
|
4
|
5027
|
//
// JSONParsing.swift
// Freddy
//
// Created by Matthew D. Mathias on 3/17/15.
// Copyright © 2015 Big Nerd Ranch. All rights reserved.
//
import Foundation
// MARK: - Deserialize JSON
/// Protocol describing a backend parser that can produce `JSON` from `NSData`.
public protocol JSONParserType {
/// Creates an instance of `JSON` from `NSData`.
/// - parameter data: An instance of `NSData` to use to create `JSON`.
/// - throws: An error that may arise from calling `JSONObjectWithData(_:options:)` on `NSJSONSerialization` with the given data.
/// - returns: An instance of `JSON`.
static func createJSONFromData(data: NSData) throws -> JSON
}
extension JSON {
/// Create `JSON` from UTF-8 `data`. By default, parses using the
/// Swift-native `JSONParser` backend.
public init(data: NSData, usingParser parser: JSONParserType.Type = JSONParser.self) throws {
self = try parser.createJSONFromData(data)
}
/// Create `JSON` from UTF-8 `string`.
public init(jsonString: Swift.String, usingParser parser: JSONParserType.Type = JSONParser.self) throws {
self = try parser.createJSONFromData((jsonString as NSString).dataUsingEncoding(NSUTF8StringEncoding) ?? NSData())
}
}
// MARK: - NSJSONSerialization
extension NSJSONSerialization: JSONParserType {
// MARK: Decode NSData
/// Use the built-in, Objective-C based JSON parser to create `JSON`.
/// - parameter data: An instance of `NSData`.
/// - returns: An instance of `JSON`.
/// - throws: An error that may arise if the `NSData` cannot be parsed into an object.
public static func createJSONFromData(data: NSData) throws -> JSON {
return makeJSON(try NSJSONSerialization.JSONObjectWithData(data, options: []))
}
// MARK: Make JSON
/// Makes a `JSON` object by matching its argument to a case in the `JSON` enum.
/// - parameter object: The instance of `AnyObject` returned from serializing the JSON.
/// - returns: An instance of `JSON` matching the JSON given to the function.
private static func makeJSON(object: AnyObject) -> JSON {
switch object {
case let n as NSNumber:
switch n {
case _ where CFNumberGetType(n) == .CharType || CFGetTypeID(n) == CFBooleanGetTypeID():
return .Bool(n.boolValue)
case _ where !CFNumberIsFloatType(n):
return .Int(n.integerValue)
default:
return .Double(n.doubleValue)
}
case let arr as [AnyObject]:
return makeJSONArray(arr)
case let dict as [Swift.String: AnyObject]:
return makeJSONDictionary(dict)
case let s as Swift.String:
return .String(s)
default:
return .Null
}
}
// MARK: Make a JSON Array
/// Makes a `JSON` array from the object passed in.
/// - parameter jsonArray: The array to transform into a `JSON`.
/// - returns: An instance of `JSON` matching the array.
private static func makeJSONArray(jsonArray: [AnyObject]) -> JSON {
return .Array(jsonArray.map(makeJSON))
}
// MARK: Make a JSON Dictionary
/// Makes a `JSON` dictionary from the Cocoa dictionary passed in.
/// - parameter jsonDict: The dictionary to transform into `JSON`.
/// - returns: An instance of `JSON` matching the dictionary.
private static func makeJSONDictionary(jsonDict: [Swift.String: AnyObject]) -> JSON {
return JSON(jsonDict.lazy.map { (key, value) in
(key, makeJSON(value))
})
}
}
// MARK: - Serialize JSON
extension JSON {
/// Attempt to serialize `JSON` into an `NSData`.
/// - returns: A byte-stream containing the `JSON` ready for wire transfer.
/// - throws: Errors that arise from `NSJSONSerialization`.
/// - see: Foundation.NSJSONSerialization
public func serialize() throws -> NSData {
let obj: AnyObject = toNSJSONSerializationObject()
return try NSJSONSerialization.dataWithJSONObject(obj, options: [])
}
/// A function to help with the serialization of `JSON`.
/// - returns: An `AnyObject` suitable for `NSJSONSerialization`'s use.
private func toNSJSONSerializationObject() -> AnyObject {
switch self {
case .Array(let jsonArray):
return jsonArray.map { $0.toNSJSONSerializationObject() }
case .Dictionary(let jsonDictionary):
var cocoaDictionary = Swift.Dictionary<Swift.String, AnyObject>(minimumCapacity: jsonDictionary.count)
for (key, json) in jsonDictionary {
cocoaDictionary[key] = json.toNSJSONSerializationObject()
}
return cocoaDictionary
case .String(let str):
return str
case .Double(let num):
return num
case .Int(let int):
return int
case .Bool(let b):
return b
case .Null:
return NSNull()
}
}
}
|
mit
|
d7e0badb93fea545d0a3ea0695d613d6
| 35.158273 | 133 | 0.63649 | 4.548416 | false | false | false | false |
Annyv2/blog-iosmagiclink
|
Passwordless-Email/WelcomeViewController.swift
|
1
|
1828
|
// WelcomeViewController.swift
//
// Copyright (c) 2015 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Lock
class WelcomeViewController: UIViewController {
@IBAction func tryLock(sender: AnyObject) {
let lock = Application.sharedInstance.lock
let controller = lock.newEmailViewController()
controller.useMagicLink = true
controller.onAuthenticationBlock = { (profile, token) in
let app = Application.sharedInstance
app.token = token
app.profile = profile
self.dismissViewControllerAnimated(true, completion: { self.performSegueWithIdentifier("UserLoggedIn", sender: self) })
}
lock.presentEmailController(controller, fromController: self)
}
}
|
mit
|
03b6b8b469a92494947c08f37aa9a655
| 43.585366 | 131 | 0.733042 | 4.810526 | false | false | false | false |
kstaring/swift
|
test/expr/closure/trailing.swift
|
4
|
14982
|
// RUN: %target-parse-verify-swift
@discardableResult
func takeFunc(_ f: (Int) -> Int) -> Int {}
func takeValueAndFunc(_ value: Int, _ f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, _ g: (Int) -> Int) {}
func takeFuncWithDefault(f : ((Int) -> Int)? = nil) {}
func takeTwoFuncsWithDefaults(f1 : ((Int) -> Int)? = nil, f2 : ((String) -> String)? = nil) {}
struct X {
func takeFunc(_ f: (Int) -> Int) {}
func takeValueAndFunc(_ value: Int, f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, g: (Int) -> Int) {}
}
func addToMemberCalls(_ x: X) {
x.takeFunc() { x in x }
x.takeFunc() { $0 }
x.takeValueAndFunc(1) { x in x }
x.takeTwoFuncs({ x in x }) { y in y }
}
func addToCalls() {
takeFunc() { x in x }
takeFunc() { $0 }
takeValueAndFunc(1) { x in x }
takeTwoFuncs({ x in x }) { y in y }
}
func makeCalls() {
takeFunc { x in x }
takeFunc { $0 }
takeTwoFuncs ({ x in x }) { y in y }
}
func notPostfix() {
_ = 1 + takeFunc { $0 }
}
class C {
func map(_ x: (Int) -> Int) -> C { return self }
func filter(_ x: (Int) -> Bool) -> C { return self }
}
var a = C().map {$0 + 1}.filter {$0 % 3 == 0}
var b = C().map {$0 + 1}
.filter {$0 % 3 == 0}
var c = C().map
{
$0 + 1
}
var c2 = C().map // expected-note{{parsing trailing closure for this call}}
{ // expected-warning{{trailing closure is separated from call site}}
$0 + 1
}
var c3 = C().map // expected-note{{parsing trailing closure for this call}}
// blah blah blah
{ // expected-warning{{trailing closure is separated from call site}}
$0 + 1
}
// Calls with multiple trailing closures should be rejected until we have time
// to design it right.
// <rdar://problem/16835718> Ban multiple trailing closures
func multiTrailingClosure(_ a : () -> (), b : () -> ()) { // expected-note {{'multiTrailingClosure(_:b:)' declared here}}
multiTrailingClosure({}) {} // ok
multiTrailingClosure {} {} // expected-error {{missing argument for parameter #1 in call}} expected-error {{consecutive statements on a line must be separated by ';'}} {{26-26=;}} expected-error {{braced block of statements is an unused closure}} expected-error{{expression resolves to an unused function}}
}
func labeledArgumentAndTrailingClosure() {
// Trailing closures can bind to labeled parameters.
takeFuncWithDefault { $0 + 1 }
takeFuncWithDefault() { $0 + 1 }
// ... but not non-trailing closures.
takeFuncWithDefault({ $0 + 1 }) // expected-error {{missing argument label 'f:' in call}} {{23-23=f: }}
takeFuncWithDefault(f: { $0 + 1 })
// Trailing closure binds to last parameter, always.
takeTwoFuncsWithDefaults { "Hello, " + $0 }
takeTwoFuncsWithDefaults { $0 + 1 } // expected-error {{cannot convert value of type '(_) -> Int' to expected argument type '((String) -> String)?'}}
takeTwoFuncsWithDefaults(f1: {$0 + 1 })
}
// rdar://problem/17965209
func rdar17965209_f<T>(_ t: T) {}
func rdar17965209(x: Int = 0, _ handler: (_ y: Int) -> ()) {}
func rdar17965209_test() {
rdar17965209() {
(y) -> () in
rdar17965209_f(1)
}
rdar17965209(x: 5) {
(y) -> () in
rdar17965209_f(1)
}
}
// <rdar://problem/22298549> QoI: Unwanted trailing closure produces weird error
func limitXY(_ xy:Int, toGamut gamut: [Int]) {}
let someInt = 0
let intArray = [someInt]
limitXY(someInt, toGamut: intArray) {} // expected-error {{extra argument 'toGamut' in call}}
// <rdar://problem/23036383> QoI: Invalid trailing closures in stmt-conditions produce lowsy diagnostics
func retBool(x: () -> Int) -> Bool {}
func maybeInt(_: () -> Int) -> Int? {}
class Foo23036383 {
init() {}
func map(_: (Int) -> Int) -> Int? {}
func meth1(x: Int, _: () -> Int) -> Bool {}
func meth2(_: Int, y: () -> Int) -> Bool {}
func filter(by: (Int) -> Bool) -> [Int] {}
}
enum MyErr : Error {
case A
}
func r23036383(foo: Foo23036383?, obj: Foo23036383) {
if retBool(x: { 1 }) { } // OK
if (retBool { 1 }) { } // OK
if retBool{ 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-13=(x: }} {{18-18=)}}
}
if retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-14=(x: }} {{19-19=)}}
}
if retBool() { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{14-16=x: }} {{21-21=)}}
} else if retBool( ) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{21-24=x: }} {{29-29=)}}
}
if let _ = maybeInt { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
}
if let _ = maybeInt { 1 } , true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
}
if let _ = foo?.map {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{29-29=)}}
}
if let _ = foo?.map() {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{23-25=}} {{31-31=)}}
}
if let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{26-27=(x: }} {{32-32=)}}
}
if obj.meth1(x: 1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{20-22=, }} {{27-27=)}}
}
if obj.meth2(1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-19=, y: }} {{24-24=)}}
}
for _ in obj.filter {$0 > 4} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}}
}
for _ in obj.filter {$0 > 4} where true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}}
}
for _ in [1,2] where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{31-32=(x: }} {{37-37=)}}
}
while retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{16-17=(x: }} {{22-22=)}}
}
while let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{29-30=(x: }} {{35-35=)}}
}
switch retBool { return 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-18=(x: }} {{30-30=)}}
default: break
}
do {
throw MyErr.A;
} catch MyErr.A where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{32-33=(x: }} {{38-38=)}}
} catch { }
if let _ = maybeInt { 1 }, retBool { 1 } { }
// expected-error@-1 {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
// expected-error@-2 {{trailing closure requires parentheses for disambiguation in this context}} {{37-38=(x: }} {{43-43=)}}
}
func overloadOnLabel(a: () -> Void) {}
func overloadOnLabel(b: () -> Void) {}
func overloadOnLabel(c: () -> Void) {}
func overloadOnLabel2(a: () -> Void) {}
func overloadOnLabel2(_: () -> Void) {}
func overloadOnLabelArgs(_: Int, a: () -> Void) {}
func overloadOnLabelArgs(_: Int, b: () -> Void) {}
func overloadOnLabelArgs2(_: Int, a: () -> Void) {}
func overloadOnLabelArgs2(_: Int, _: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 0, a: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 1, b: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 0, a: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 1, b: () -> Void) {}
func overloadOnDefaultArgsOnly(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly(y: Int = 1, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(y: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, y: Int = 1, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, y: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func testOverloadAmbiguity() {
overloadOnLabel {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{18-19=(a: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{18-19=(b: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{18-19=(c: }} {{21-21=)}}
overloadOnLabel() {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{19-21=a: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{19-21=b: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{19-21=c: }} {{23-23=)}}
overloadOnLabel2 {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{19-20=(a: }} {{22-22=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{19-20=(}} {{22-22=)}}
overloadOnLabel2() {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{20-22=a: }} {{24-24=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{20-22=}} {{24-24=)}}
overloadOnLabelArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:a:)'}} {{24-26=, a: }} {{28-28=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:b:)'}} {{24-26=, b: }} {{28-28=)}}
overloadOnLabelArgs2(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs2(_:a:)'}} {{25-27=, a: }} {{29-29=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabelArgs2'}} {{25-27=, }} {{29-29=)}}
overloadOnLabelDefaultArgs {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{29-30=(a: }} {{32-32=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{29-30=(b: }} {{32-32=)}}
overloadOnLabelDefaultArgs() {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{30-32=a: }} {{34-34=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{30-32=b: }} {{34-34=)}}
overloadOnLabelDefaultArgs(x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{34-36=, a: }} {{38-38=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{34-36=, b: }} {{38-38=)}}
overloadOnLabelSomeDefaultArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{35-37=, a: }} {{39-39=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{35-37=, b: }} {{39-39=)}}
overloadOnLabelSomeDefaultArgs(1, x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{41-43=, a: }} {{45-45=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{41-43=, b: }} {{45-45=)}}
overloadOnLabelSomeDefaultArgs( // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{12-5=, a: }} {{4-4=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{12-5=, b: }} {{4-4=)}}
1, x: 2
) {
// some
}
overloadOnDefaultArgsOnly {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly2 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly2() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly3 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnDefaultArgsOnly3() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnSomeDefaultArgsOnly(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly'}}
overloadOnSomeDefaultArgsOnly2(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly2'}}
overloadOnSomeDefaultArgsOnly3(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly3(_:x:a:)'}}
}
|
apache-2.0
|
9f04baaf24ba78b76f916aee353b6561
| 58.928 | 485 | 0.665732 | 3.926101 | false | false | false | false |
jamesjmtaylor/weg-ios
|
wegUnitTests/equipmentCollectionViewTests.swift
|
1
|
1478
|
//
// wegUnitTests.swift
// wegUnitTests
//
// Created by Taylor, James on 7/7/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import XCTest
@testable import weg_ios
class equipmentCollectionViewTests: XCTestCase {
var vc : EquipmentCollectionViewController?
override func setUp() {
super.setUp()
let main = UIStoryboard.init(name: "Main", bundle: nil)
vc = main.instantiateViewController(withIdentifier: "EquipmentCollectionViewController") as? EquipmentCollectionViewController
}
override func tearDown() {super.tearDown()}
func testFrameShouldHoldTwoColumns() {
let frame = CGRect(x: 0, y: 0, width: 375, height: 500)
let layout = UICollectionViewLayout()
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
let actual = EquipmentCollectionViewController.calculateNoOfColumns(cv: collectionView)
let expected : CGFloat = 2.0
XCTAssertEqual(actual, expected)
}
func testFrameShouldHoldSixColumns() {
let frame = CGRect(x: 0, y: 0, width: 1000, height: 1000)
let layout = UICollectionViewLayout()
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
let actual = EquipmentCollectionViewController.calculateNoOfColumns(cv: collectionView)
let expected : CGFloat = 6.0
XCTAssertEqual(actual, expected)
}
}
|
mit
|
e55c85525505770fb834233383a1610c
| 34.166667 | 134 | 0.686527 | 4.795455 | false | true | false | false |
ps2/rileylink_ios
|
MinimedKit/CGMManager/SensorValueGlucoseEvent+CGMManager.swift
|
1
|
572
|
//
// SensorValueGlucoseEvent.swift
// Loop
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
extension SensorValueGlucoseEvent {
var glucoseSyncIdentifier: String? {
let date = timestamp
guard
let year = date.year,
let month = date.month,
let day = date.day,
let hour = date.hour,
let minute = date.minute,
let second = date.second
else {
return nil
}
return "\(year)-\(month)-\(day) \(hour)-\(minute)-\(second)"
}
}
|
mit
|
7dc6672feba1af5aaa2f62a2a907de01
| 20.961538 | 68 | 0.532399 | 4.460938 | false | false | false | false |
sunlijian/sinaBlog_repository
|
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Model/IWStatusFrame.swift
|
1
|
6855
|
//
// IWStatusFrame.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/15.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
//定义 cell里字控件的间距
private let CELL_CHILD_VIEW_MARGIN :CGFloat = 10
//定义名字字体的大小
let CELL_STATUS_NAME_FONT: CGFloat = 14
//定义创建时间的字体大小
let CELL_STATUS_CREATE_AT_FONT: CGFloat = 10
//微博内容字体的大小
let CELL_STATUS_TEXT_FONT: CGFloat = 15
class IWStatusFrame: NSObject {
var status: IWStatus? {
didSet{
setStatus()
}
}
//整体 原创 view 的 frame
var originalViewF:CGRect?
//头像
var headImageViewF:CGRect?
//姓名
var nameLableF: CGRect?
//vip
var vipImageViewF: CGRect?
//创建时间
var created_atF: CGRect?
//来源
var sourceF: CGRect?
//原创微博内容
var textF: CGRect?
//原创微博的图片
var originalPhotosF: CGRect?
//转发微博的整体 view
var retweetViewF:CGRect?
//转发微博 内容
var retweetTextLabelF: CGRect?
//转发微博的图片
var retweetPhotosF: CGRect?
//计算底部 toolBar的frame
var statusToolBarF:CGRect?
//cell的高度
var cellHeight: CGFloat?
//计算 frame
private func setStatus(){
let status = self.status!
//----------------------------------------计算原创微博的frame-----------------------------------------------------//
//原创整体 view 的 frame
let originalViewX :CGFloat = 0
let originalViewY = CELL_CHILD_VIEW_MARGIN
let originalViewW = SCREEN_W
var originalViewH :CGFloat = 0
//头像
let headImageViewX = CELL_CHILD_VIEW_MARGIN
let headImageViewY = CELL_CHILD_VIEW_MARGIN
let headImageSize = CGSizeMake(35, 35)
headImageViewF = CGRect(origin: CGPointMake(headImageViewX, headImageViewY), size: headImageSize)
//姓名
let nameLabelX = CGRectGetMaxX(headImageViewF!) + CELL_CHILD_VIEW_MARGIN
let nameLabelY = CELL_CHILD_VIEW_MARGIN
let nameLabelSize = status.user!.name!.size(UIFont.systemFontOfSize(CELL_STATUS_NAME_FONT))
nameLableF = CGRect(origin: CGPointMake(nameLabelX, nameLabelY), size: nameLabelSize)
//会员
//frame
let vipImageViewX = CGRectGetMaxX(nameLableF!) + CELL_CHILD_VIEW_MARGIN
let vipImageViewY = headImageViewY
let vipImageVeiwSize = CGSizeMake(nameLabelSize.height, nameLabelSize.height)
vipImageViewF = CGRect(origin: CGPointMake(vipImageViewX, vipImageViewY), size: vipImageVeiwSize)
//创建时间
let created_atX = nameLabelX
let created_atSize = status.created_at!.size(UIFont.systemFontOfSize(CELL_STATUS_CREATE_AT_FONT))
let created_atY = CGRectGetMaxY(headImageViewF!) - created_atSize.height
created_atF = CGRect(origin: CGPointMake(created_atX, created_atY), size: created_atSize)
//微博来源
let sourceX = CGRectGetMaxX(created_atF!) + CELL_CHILD_VIEW_MARGIN
let sourceY = created_atY
let sourceSize = status.source?.size(UIFont.systemFontOfSize(CELL_STATUS_CREATE_AT_FONT))
sourceF = CGRect(origin: CGPointMake(sourceX, sourceY), size: sourceSize!)
//原创微博内容
let textX = CELL_CHILD_VIEW_MARGIN
let textY = CGRectGetMaxY(headImageViewF!) + CELL_CHILD_VIEW_MARGIN
let textSize = status.text?.size(UIFont.systemFontOfSize(CELL_STATUS_TEXT_FONT), constrainedToSize: CGSizeMake(SCREEN_W - 2 * CELL_CHILD_VIEW_MARGIN, CGFloat(MAXFLOAT)))
textF = CGRect(origin: CGPointMake(textX, textY), size: textSize!)
//原创微博整体 view 的 H
originalViewH = CGRectGetMaxY(textF!)
//原创微博的图片
if let originalPhotosUrls = status.pic_urls where status.pic_urls?.count > 0{
let originalPhotosX = CELL_CHILD_VIEW_MARGIN
let originalPhotosY = CGRectGetMaxY(textF!) + CELL_CHILD_VIEW_MARGIN
let originalPhotosSize = IWStatusPhotos.size(originalPhotosUrls.count)
originalPhotosF = CGRect(origin: CGPointMake(originalPhotosX, originalPhotosY), size: originalPhotosSize)
//整体 view 的 y
originalViewH = CGRectGetMaxY(originalPhotosF!)
}
//整体的 view.frame
originalViewF = CGRectMake(originalViewX, originalViewY, originalViewW, originalViewH)
//底部toolBar 的Y
var statusToolBarY = CGRectGetMaxY(originalViewF!)
//----------------------------------------计算转发微博的frame-----------------------------------------------------//
//转发微博的 frame
if let retStatus = status.retweeted_status {
//转发微博的内容frame
let retweetTextLabelX = CELL_CHILD_VIEW_MARGIN
let retweetTextLabelY = CELL_CHILD_VIEW_MARGIN
let retweetTextLabelSize = retStatus.text?.size(UIFont.systemFontOfSize(CELL_STATUS_TEXT_FONT), constrainedToSize: CGSizeMake(SCREEN_W - 2 * CELL_CHILD_VIEW_MARGIN, CGFloat(MAXFLOAT)))
retweetTextLabelF = CGRect(origin: CGPointMake(retweetTextLabelX, retweetTextLabelY), size: retweetTextLabelSize!)
var retweetViewH = CGRectGetMaxY(retweetTextLabelF!)
//转发微博的图片 frame
if let retweetPhotosUrls = retStatus.pic_urls where retStatus.pic_urls?.count>0 {
let retweetPhotosX = CELL_CHILD_VIEW_MARGIN
let retweetPhotosY = CGRectGetMaxY(retweetTextLabelF!) + CELL_CHILD_VIEW_MARGIN
let retweetPhotosSize = IWStatusPhotos.size(retweetPhotosUrls.count)
retweetPhotosF = CGRect(origin: CGPointMake(retweetPhotosX, retweetPhotosY), size: retweetPhotosSize)
retweetViewH = CGRectGetMaxY(retweetPhotosF!)
}
//转发整体 view的 frame
let retweetViewX = CGFloat(0)
let retweetViewY = CGRectGetMaxY(textF!) + CELL_CHILD_VIEW_MARGIN
let retweetViewW = SCREEN_W
retweetViewF = CGRectMake(retweetViewX, retweetViewY, retweetViewW, retweetViewH)
//重新计算底部 toolBar的y
statusToolBarY = CGRectGetMaxY(retweetViewF!)
}
//----------------------------------------计算底部toolBar微博的frame-----------------------------------------------------//
//底部 toolBar 的大小
let statusToolBarX :CGFloat = 0
let statusToolBarSize = CGSizeMake(SCREEN_W, 35)
statusToolBarF = CGRect(origin: CGPointMake(statusToolBarX, statusToolBarY), size: statusToolBarSize)
//cell的高度
cellHeight = CGRectGetMaxY(statusToolBarF!)
}
}
|
apache-2.0
|
48446e231a4b157a4eb53e61bb51f71e
| 41.675497 | 196 | 0.63144 | 4.368814 | false | false | false | false |
inamiy/ReactiveCocoaCatalog
|
ReactiveCocoaCatalog/Samples/GameCommandViewController.swift
|
1
|
3674
|
//
// GameCommandViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-20.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
///
/// Street Fighter Super-Move-Command example.
///
/// - SeeAlso:
/// - [Street Fighter - Wikipedia, the free encyclopedia](https://en.wikipedia.org/wiki/Street_Fighter)
///
final class GameCommandViewController: UIViewController, StoryboardSceneProvider
{
static let storyboardScene = StoryboardScene<GameCommandViewController>(name: "GameCommand")
@IBOutlet var buttons: [UIButton]?
@IBOutlet weak var effectLabel: UILabel?
override func viewDidLoad()
{
super.viewDidLoad()
let buttonTaps = self.buttons!
.map { $0.reactive.controlEvents(.touchUpInside) }
// NOTE: Commands are evaluated from button's title using easy IBOutletCollection.
let commands = SignalProducer<Signal<UIButton, NoError>, NoError>(buttonTaps).flatten(.merge)
.map { GameCommand(rawValue: $0.title(for: .normal)!) }
.skipNil()
.on(event: logSink("commands"))
let d = commands
.promoteErrors(GameCommand.Error.self)
.flatMap(.latest) {
SignalProducer(value: $0)
.concat(.never)
.timeout(after: 1, raising: .timeout, on: QueueScheduler.main)
}
.scan([]) { $0 + [$1] }
.map { SuperMove(command: $0.map { $0.rawValue }.joined(separator: "")) }
.skipNil()
.take(first: 1)
.forever()
.ignoreCastError(NoError.self)
.startWithValues { [unowned self] command in
print("\n_人人 人人 人人_\n" + "> \(command) <\n" + " ̄Y^Y^Y^Y^Y^Y ̄")
_zoomOut(label: self.effectLabel!, text: "\(command)")
}
self.reactive.lifetime.ended.observeCompleted {
d.dispose()
}
}
}
// MARK: GameCommand
enum GameCommand: String
{
// case ➡️, ↘️, ⬇️, ↙️, ⬅️, ↖️, ⬆️, ↗️, 👊, 👣 // Comment-Out: Can't do this 😡💢
// NOTE: Mapped to Storyboard labels.
case right = "➡️", downRight = "↘️", down = "⬇️", downLeft = "↙️", left = "⬅️", upLeft = "↖️", up = "⬆️", upRight = "↗️"
case punch = "👊", kick = "👣"
}
extension GameCommand
{
enum Error: Swift.Error
{
case timeout
}
}
// MARK: SuperMove
/// - SeeAlso: [Inputs - Street Fighter Wiki - Wikia](http://streetfighter.wikia.com/wiki/Inputs)
enum SuperMove: String
{
case hadouken = "⬇️↘️➡️👊"
case shoryuken = "➡️⬇️↘️👊"
case tatsumakiSenpukyaku = "⬇️↙️⬅️👣" // a.k.a "Hurricane Kick"
case screwPileDriver = "➡️↘️⬇️↙️⬅️↖️⬆️↗️👊" // a.k.a. "Spinning Pile Driver"
static let allValues = [hadouken, shoryuken, tatsumakiSenpukyaku, screwPileDriver]
/// - Returns: Preferred `SuperMove` evaluated from `command` **suffix**.
init?(command: String)
{
for value in SuperMove.allValues {
if command.hasSuffix(value.rawValue) {
self = value
return
}
}
return nil
}
}
// MARK: Helpers
private func _zoomOut(label: UILabel, text: String)
{
label.text = "\(text)"
label.alpha = 1
label.transform = CGAffineTransform.identity
UIView.animate(withDuration: 0.5) {
label.alpha = 0
label.transform = CGAffineTransform(scaleX: 3, y: 3)
}
}
|
mit
|
2e24d5dc43fe8ae9dbec4e2bbdd8b8b8
| 28.058333 | 124 | 0.577574 | 3.515121 | false | false | false | false |
mixalich7b/SwiftTBot
|
Examples/EchoBotLinuxExample/Sources/EchoBotLinuxExample/main.swift
|
1
|
5178
|
import Foundation
import SwiftTBot
private let bot = TBot(token: "<your_token>")
fileprivate func getRandomNum(_ min: Int, _ max: Int) -> Int {
#if os(Linux)
return Int(random() % max) + min
#else
return Int(arc4random_uniform(UInt32(max)) + UInt32(min))
#endif
}
bot.on("/start") { "Hello, \($0.from?.firstName ?? $0.chat.firstName ?? "" )"}
.on("/test") { _ in "It's work"}
.on("/info") {[weak bot] (message, textReply) in
do {
try bot?.sendRequest(TBGetMeRequest(), completion: { (response) in
if let username = response.responseEntities?.first?.username {
textReply.send("\(username)\nhttps://telegram.me/\(username)")
}
})
} catch {
}
}
let awesomeCommandRegex = try! NSRegularExpression(
pattern: "^(\\/awesome)\\s([0-9]{1,4})\\s([0-9]{1,4})$",
options: NSRegularExpression.Options(rawValue: 0)
)
let argsParsingRegex = try! NSRegularExpression(
pattern: "([0-9]{1,4})",
options: NSRegularExpression.Options(rawValue: 0)
)
bot.on(awesomeCommandRegex) { (message, matchRange, textReply) in
guard let text = message.text else {
return
}
let replyString = argsParsingRegex.matches(
in: text,
options: NSRegularExpression.MatchingOptions.reportProgress,
range: matchRange)
.reduce("Args: ") { (replyText, checkResult) -> String in
return replyText + (text as NSString).substring(with: checkResult.range) + ", "
}
textReply.send(replyString)
}
bot.onInline(awesomeCommandRegex) { (inlineQuery, range, inlineQueryReply) in
let article1 = TBInlineQueryResultArticle(
id: "\(getRandomNum(0, 1000))",
title: "Test title",
inputMessageContent: TBInputTextMessageContent(messageText: "Test text")
)
article1.url = "google.com"
inlineQueryReply.send([article1])
}
bot.start { (error) in
print("Bot haven't started, error: \(error?.description ?? "unknown")")
}
private func respondToMessage(_ message: TBMessage) {
let text = message.text
let contact = message.contact
let location = message.location
let replyText = text
?? contact.map{"\($0.phoneNumber), \($0.firstName)"}
?? location?.debugDescription ?? "Hello!"
let replyHTML = "<i>\(replyText)</i>\n<a href='http://www.instml.com/'>Instaml</a>";
let keyboard = TBReplyKeyboardMarkup(buttons: [
[TBKeyboardButton(text: "Contact", requestContact: true)],
[TBKeyboardButton(text: "Location", requestLocation: true)]
]);
keyboard.selective = true
keyboard.oneTimeKeyboard = true
let echoRequest = TBSendMessageRequest(
chatId: message.chat.id,
text: replyHTML,
replyMarkup: keyboard,
parseMode: .HTML
)
do {
try bot.sendRequest(echoRequest, completion: { (response) in
if !response.isOk {
print("API error: \(response.error?.description ?? "unknown")")
}
})
} catch TBError.badRequest {
print("Bad request")
} catch {
print("")
}
}
private func respondToInlineQuery(_ inlineQuery: TBInlineQuery) {
let article1 = TBInlineQueryResultArticle(
id: "\(getRandomNum(0, 1000))",
title: "Test title",
inputMessageContent: TBInputTextMessageContent(messageText: "Test text")
)
article1.url = "google.com"
let article2 = TBInlineQueryResultArticle(
id: "\(getRandomNum(0, 1000))",
title: "Awesome article",
inputMessageContent: TBInputLocationMessageContent(longitude: 98.292905, latitude: 7.817627)
)
article2.url = "vk.com"
let btn1 = TBInlineKeyboardButton(text: "Btn1")
btn1.url = "2ch.hk/b"
btn1.callbackData = "btn1"
let btn2 = TBInlineKeyboardButton(text: "Btn2")
btn2.callbackData = "btn2"
btn2.switchInlineQuery = "switch inline btn2"
let btn3 = TBInlineKeyboardButton(text: "Btn3")
btn3.callbackData = "btn3"
let replyKeyboardMarkup = TBInlineKeyboardMarkup(buttons: [[btn1, btn2], [btn3]])
let article3 = TBInlineQueryResultArticle(id: "\(getRandomNum(0, 1000))",
title: "Echo result",
inputMessageContent: TBInputTextMessageContent(messageText: "Echo: \(inlineQuery.text)"),
replyKeyboardMarkup: replyKeyboardMarkup
)
article3.url = "youtube.com"
article3.description = "Echo: \(inlineQuery.text),\noffset: \(inlineQuery.offset)"
let answerInlineRequest = TBAnswerInlineQueryRequest(
inlineRequestId: inlineQuery.id,
results: [article1, article2, article3]
)
answerInlineRequest.switchPMText = "Go PM"
answerInlineRequest.switchPMParameter = "info"
answerInlineRequest.cacheTimeSeconds = 5
do {
try bot.sendRequest(answerInlineRequest, completion: { (response) in
if !response.isOk {
print("API error: \(response.error?.description ?? "unknown")")
}
})
} catch TBError.badRequest {
print("Bad request")
} catch {
print("")
}
}
let _ = readLine()
bot.stop()
|
gpl-3.0
|
2371d5e2543e8b50419dbc1cec773d86
| 32.843137 | 100 | 0.62978 | 4.061176 | false | false | false | false |
0x73/Cherry
|
Cherry WatchKit Extension/InterfaceControllers/KTWatchAddActivityInterfaceController.swift
|
7
|
1823
|
//
// KTWatchAddActivityInterfaceController.swift
// Cherry
//
// Created by Kenny Tang on 2/24/15.
//
//
import WatchKit
import Foundation
class KTWatchAddActivityInterfaceController: WKInterfaceController {
var activityName:String?
var expectedPomos:Int = 1
@IBOutlet weak var expectedPomosLabel:WKInterfaceLabel?
@IBOutlet weak var confirmButton:WKInterfaceButton?
@IBOutlet weak var activityNameButton:WKInterfaceButton?
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
// MARK: Action Handlers
@IBAction func enterActivityNameButtonTapped() {
self.presentTextInputControllerWithSuggestions([
"Watch Cat Videos",
"Exercise",
"Do some writing",
"Practice the guitar",
"Read a book",
"Work"], allowedInputMode: WKTextInputMode.Plain, completion:{(selectedAnswers) -> Void in
if let activityName = selectedAnswers?[0] as? String {
self.activityName = activityName
self.activityNameButton!.setTitle(activityName)
self.confirmButton!.setEnabled(true)
self.confirmButton!.setHidden(false)
}
})
}
@IBAction func confirmButtonTapped() {
if let name = self.activityName {
KTCoreDataStack.sharedInstance.createActivity(name, desc: "", pomos: self.expectedPomos)
KTCoreDataStack.sharedInstance.saveContext()
}
self.dismissController()
}
@IBAction func pomoSliderValueChanged(value:CGFloat) {
self.expectedPomos = Int(floor(value))
self.expectedPomosLabel!.setText("\(self.expectedPomos)")
}
}
|
mit
|
09c3e96d5aecf1c7cf411ce855e542dc
| 30.982456 | 103 | 0.646188 | 4.772251 | false | false | false | false |
wjk930726/weibo
|
weiBo/weiBo/iPhone/Utilities/Category/Date+WJKAddition.swift
|
1
|
2419
|
//
// Date+WJKAddition.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/30.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
private let dateFromat = DateFormatter()
private let calendar = Calendar.current
extension Date {
static func dateFromSinaFormat(sinaDateString: String) -> Date {
dateFromat.locale = Locale(identifier: "en")
dateFromat.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
return dateFromat.date(from: sinaDateString)!
}
struct todayData {
var weekday: String?
var monthAndYear: String?
var day: String?
}
static func today() -> todayData {
var date = todayData()
let today = Date()
let weekdays = [nil, "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", nil]
let day = calendar.component(Calendar.Component.weekday, from: today)
date.weekday = weekdays[day]
dateFromat.dateFormat = "MM/yyyy"
dateFromat.locale = Locale(identifier: "en")
date.monthAndYear = dateFromat.string(from: today)
dateFromat.dateFormat = "d"
date.day = dateFromat.string(from: today)
return date
}
public func requiredTimeString() -> String {
if calendar.isDateInToday(self) {
let secends = -Int(timeIntervalSinceNow)
if secends < 60 {
return "刚刚"
} else if secends < 3600 {
return "\(secends / 60)分钟前"
} else {
return "\(secends / 3600)小时前"
}
} else if calendar.isDateInYesterday(self) {
dateFromat.locale = Locale(identifier: "en")
dateFromat.dateFormat = "昨天 HH:mm"
return "\(dateFromat.string(from: self))"
} else {
let thisYear = calendar.component(.year, from: Date())
let hisYear = calendar.component(.year, from: self)
if thisYear == hisYear {
dateFromat.dateFormat = "MM-dd HH: mm"
dateFromat.locale = Locale(identifier: "en")
return "\(dateFromat.string(from: self))"
} else {
dateFromat.dateFormat = "yyyy-MM-dd HH: mm"
dateFromat.locale = Locale(identifier: "en")
return "\(dateFromat.string(from: self))"
}
}
}
}
|
mit
|
06f3c07420636c4a1f1ba25d434e0a6f
| 31.054795 | 82 | 0.56453 | 4.105263 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
UIKit/UIViewControllerTransitioningDelegate/UIViewControllerTransitioningDelegate/PresentedViewController.swift
|
1
|
981
|
//
// PresentedViewController.swift
// UIViewControllerTransitioningDelegate
//
// Created by pantosoft on 2018/7/24.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
class PresentedViewController: UIViewController {
@IBOutlet var gestureRecognizer: UIPanGestureRecognizer!
@IBAction func didPan(_ sender: UIPanGestureRecognizer) {
if sender.state == .began {
performSegue(withIdentifier: "CustomDismissInteractiveAnimator", sender: sender)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier, identifier == "CustomDismissInteractiveAnimator" {
if let customInteractiveTransition1Delegate = self.transitioningDelegate as? CustomInteractiveTransition1Delegate, let gesture = sender as? UIPanGestureRecognizer{
customInteractiveTransition1Delegate.gestureRecognizer = gesture
}
}
}
}
|
mit
|
7bb6b5ceec38503c4b000f6edb200ea1
| 36.615385 | 175 | 0.719836 | 5.525424 | false | false | false | false |
azadibogolubov/InterestDestroyer
|
iOS Version/Interest Destroyer/Charts/Classes/Data/ChartData.swift
|
16
|
25627
|
//
// ChartData.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
import UIKit
public class ChartData: NSObject
{
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _leftAxisMax = Double(0.0)
internal var _leftAxisMin = Double(0.0)
internal var _rightAxisMax = Double(0.0)
internal var _rightAxisMin = Double(0.0)
private var _yValueSum = Double(0.0)
private var _yValCount = Int(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
/// the average length (in characters) across all x-value strings
private var _xValAverageLength = Double(0.0)
internal var _xVals: [String?]!
internal var _dataSets: [ChartDataSet]!
public override init()
{
super.init()
_xVals = [String?]()
_dataSets = [ChartDataSet]()
}
public init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : xVals
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!)
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public convenience init(xVals: [String?]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [NSObject]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [String?]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [ChartDataSet])
{
checkIsLegal(dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
// calculates the average length (in characters) across all x-value strings
internal func calcXValAverageLength()
{
if (_xVals.count == 0)
{
_xValAverageLength = 1
return
}
var sum = 1
for (var i = 0; i < _xVals.count; i++)
{
sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count
}
_xValAverageLength = Double(sum) / Double(_xVals.count)
}
// Checks if the combination of x-values array and DataSet array is legal or not.
// :param: dataSets
internal func checkIsLegal(dataSets: [ChartDataSet]!)
{
if (dataSets == nil)
{
return
}
if self is ScatterChartData
{ // In scatter chart it makes sense to have more than one y-value value for an x-index
return
}
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].yVals.count > _xVals.count)
{
print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n")
return
}
}
}
public func notifyDataChanged()
{
initialize(_dataSets)
}
/// calc minimum and maximum y value over all datasets
internal func calcMinMax(start start: Int, end: Int)
{
if (_dataSets == nil || _dataSets.count < 1)
{
_yMax = 0.0
_yMin = 0.0
}
else
{
_lastStart = start
_lastEnd = end
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = 0; i < _dataSets.count; i++)
{
_dataSets[i].calcMinMax(start: start, end: end)
if (_dataSets[i].yMin < _yMin)
{
_yMin = _dataSets[i].yMin
}
if (_dataSets[i].yMax > _yMax)
{
_yMax = _dataSets[i].yMax
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
// left axis
let firstLeft = getFirstLeft()
if (firstLeft !== nil)
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
if (dataSet.yMin < _leftAxisMin)
{
_leftAxisMin = dataSet.yMin
}
if (dataSet.yMax > _leftAxisMax)
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight()
if (firstRight !== nil)
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
if (dataSet.yMin < _rightAxisMin)
{
_rightAxisMin = dataSet.yMin
}
if (dataSet.yMax > _rightAxisMax)
{
_rightAxisMax = dataSet.yMax
}
}
}
}
// in case there is only one axis, adjust the second axis
handleEmptyAxis(firstLeft, firstRight: firstRight)
}
}
/// calculates the sum of all y-values in all datasets
internal func calcYValueSum()
{
_yValueSum = 0
if (_dataSets == nil)
{
return
}
for (var i = 0; i < _dataSets.count; i++)
{
_yValueSum += fabs(_dataSets[i].yValueSum)
}
}
/// Calculates the total number of y-values across all ChartDataSets the ChartData represents.
internal func calcYValueCount()
{
_yValCount = 0
if (_dataSets == nil)
{
return
}
var count = 0
for (var i = 0; i < _dataSets.count; i++)
{
count += _dataSets[i].entryCount
}
_yValCount = count
}
/// - returns: the number of LineDataSets this object contains
public var dataSetCount: Int
{
if (_dataSets == nil)
{
return 0
}
return _dataSets.count
}
/// - returns: the average value across all entries in this Data object (all entries from the DataSets this data object holds)
public var average: Double
{
return yValueSum / Double(yValCount)
}
/// - returns: the smallest y-value the data object contains.
public var yMin: Double
{
return _yMin
}
public func getYMin() -> Double
{
return _yMin
}
public func getYMin(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
/// - returns: the greatest y-value the data object contains.
public var yMax: Double
{
return _yMax
}
public func getYMax() -> Double
{
return _yMax
}
public func getYMax(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValAverageLength: Double
{
return _xValAverageLength
}
/// - returns: the total y-value sum across all DataSet objects the this object represents.
public var yValueSum: Double
{
return _yValueSum
}
/// - returns: the total number of y-values across all DataSet objects the this object represents.
public var yValCount: Int
{
return _yValCount
}
/// - returns: the x-values the chart represents
public var xVals: [String?]
{
return _xVals
}
///Adds a new x-value to the chart data.
public func addXValue(xVal: String?)
{
_xVals.append(xVal)
}
/// Removes the x-value at the specified index.
public func removeXValue(index: Int)
{
_xVals.removeAtIndex(index)
}
/// - returns: the array of ChartDataSets this object holds.
public var dataSets: [ChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - parameter dataSets: the DataSet array to search
/// - parameter type:
/// - parameter ignorecase: if true, the search is not case-sensitive
/// - returns: the index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int
{
if (ignorecase)
{
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame)
{
return i
}
}
}
else
{
for (var i = 0; i < dataSets.count; i++)
{
if (label == dataSets[i].label)
{
return i
}
}
}
return -1
}
/// - returns: the total number of x-values this ChartData object represents (the size of the x-values array)
public var xValCount: Int
{
return _xVals.count
}
/// - returns: the labels of all DataSets as a string array.
internal func dataSetLabels() -> [String]
{
var types = [String]()
for (var i = 0; i < _dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
types[i] = _dataSets[i].label!
}
return types
}
/// Get the Entry for a corresponding highlight object
///
/// - parameter highlight:
/// - returns: the entry that is highlighted
public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - parameter label:
/// - parameter ignorecase:
/// - returns: the DataSet Object with the given label. Sensitive or not.
public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if (index < 0 || index >= _dataSets.count)
{
return nil
}
else
{
return _dataSets[index]
}
}
public func getDataSetByIndex(index: Int) -> ChartDataSet!
{
if (_dataSets == nil || index < 0 || index >= _dataSets.count)
{
return nil
}
return _dataSets[index]
}
public func addDataSet(d: ChartDataSet!)
{
if (_dataSets == nil)
{
return
}
_yValCount += d.entryCount
_yValueSum += d.yValueSum
if (_dataSets.count == 0)
{
_yMax = d.yMax
_yMin = d.yMin
if (d.axisDependency == .Left)
{
_leftAxisMax = d.yMax
_leftAxisMin = d.yMin
}
else
{
_rightAxisMax = d.yMax
_rightAxisMin = d.yMin
}
}
else
{
if (_yMax < d.yMax)
{
_yMax = d.yMax
}
if (_yMin > d.yMin)
{
_yMin = d.yMin
}
if (d.axisDependency == .Left)
{
if (_leftAxisMax < d.yMax)
{
_leftAxisMax = d.yMax
}
if (_leftAxisMin > d.yMin)
{
_leftAxisMin = d.yMin
}
}
else
{
if (_rightAxisMax < d.yMax)
{
_rightAxisMax = d.yMax
}
if (_rightAxisMin > d.yMin)
{
_rightAxisMin = d.yMin
}
}
}
_dataSets.append(d)
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
}
public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?)
{
// in case there is only one axis, adjust the second axis
if (firstLeft === nil)
{
_leftAxisMax = _rightAxisMax
_leftAxisMin = _rightAxisMin
}
else if (firstRight === nil)
{
_rightAxisMax = _leftAxisMax
_rightAxisMin = _leftAxisMin
}
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSet(dataSet: ChartDataSet!) -> Bool
{
if (_dataSets == nil || dataSet === nil)
{
return false
}
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return removeDataSetByIndex(i)
}
}
return false
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSetByIndex(index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false
}
let d = _dataSets.removeAtIndex(index)
_yValCount -= d.entryCount
_yValueSum -= d.yValueSum
calcMinMax(start: _lastStart, end: _lastEnd)
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
public func addEntry(e: ChartDataEntry, dataSetIndex: Int)
{
if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0)
{
let val = e.value
let set = _dataSets[dataSetIndex]
if (_yValCount == 0)
{
_yMin = val
_yMax = val
if (set.axisDependency == .Left)
{
_leftAxisMax = e.value
_leftAxisMin = e.value
}
else
{
_rightAxisMax = e.value
_rightAxisMin = e.value
}
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
if (set.axisDependency == .Left)
{
if (_leftAxisMax < e.value)
{
_leftAxisMax = e.value
}
if (_leftAxisMin > e.value)
{
_leftAxisMin = e.value
}
}
else
{
if (_rightAxisMax < e.value)
{
_rightAxisMax = e.value
}
if (_rightAxisMin > e.value)
{
_rightAxisMin = e.value
}
}
}
_yValCount += 1
_yValueSum += val
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
set.addEntry(e)
}
else
{
print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool
{
// entry null, outofbounds
if (entry === nil || dataSetIndex >= _dataSets.count)
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex)
if (removed)
{
let val = entry.value
_yValCount -= 1
_yValueSum -= val
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
/// Removes the Entry object at the given xIndex from the ChartDataSet at the
/// specified index.
/// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements.
public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool
{
if (dataSetIndex >= _dataSets.count)
{
return false
}
let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex)
if (entry?.xIndex != xIndex)
{
return false
}
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
/// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet?
{
if (e == nil)
{
return nil
}
for (var i = 0; i < _dataSets.count; i++)
{
let set = _dataSets[i]
for (var j = 0; j < set.entryCount; j++)
{
if (e === set.entryForXIndex(e.xIndex))
{
return set
}
}
}
return nil
}
/// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found.
public func indexOfDataSet(dataSet: ChartDataSet) -> Int
{
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return i
}
}
return -1
}
/// - returns: the first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found.
public func getFirstLeft() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
return dataSet
}
}
return nil
}
/// - returns: the first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found.
public func getFirstRight() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
return dataSet
}
}
return nil
}
/// - returns: all colors used across all DataSet objects this object represents.
public func getColors() -> [UIColor]?
{
if (_dataSets == nil)
{
return nil
}
var clrcnt = 0
for (var i = 0; i < _dataSets.count; i++)
{
clrcnt += _dataSets[i].colors.count
}
var colors = [UIColor]()
for (var i = 0; i < _dataSets.count; i++)
{
let clrs = _dataSets[i].colors
for clr in clrs
{
colors.append(clr)
}
}
return colors
}
/// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience.
public func generateXVals(from: Int, to: Int) -> [String]
{
var xvals = [String]()
for (var i = from; i < to; i++)
{
xvals.append(String(i))
}
return xvals
}
/// Sets a custom ValueFormatter for all DataSets this data object contains.
public func setValueFormatter(formatter: NSNumberFormatter!)
{
for set in dataSets
{
set.valueFormatter = formatter
}
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
public func setValueTextColor(color: UIColor!)
{
for set in dataSets
{
set.valueTextColor = color ?? set.valueTextColor
}
}
/// Sets the font for all value-labels for all DataSets this data object contains.
public func setValueFont(font: UIFont!)
{
for set in dataSets
{
set.valueFont = font ?? set.valueFont
}
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
public func setDrawValues(enabled: Bool)
{
for set in dataSets
{
set.drawValuesEnabled = enabled
}
}
/// Enables / disables highlighting values for all DataSets this data object contains.
public var highlightEnabled: Bool
{
get
{
for set in dataSets
{
if (!set.highlightEnabled)
{
return false
}
}
return true
}
set
{
for set in dataSets
{
set.highlightEnabled = newValue
}
}
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
public func clearValues()
{
dataSets.removeAll(keepCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified Entry.
/// - returns: true if so, false if not.
public func contains(entry entry: ChartDataEntry) -> Bool
{
for set in dataSets
{
if (set.contains(entry))
{
return true
}
}
return false
}
/// Checks if this data object contains the specified DataSet.
/// - returns: true if so, false if not.
public func contains(dataSet dataSet: ChartDataSet) -> Bool
{
for set in dataSets
{
if (set.isEqual(dataSet))
{
return true
}
}
return false
}
/// MARK: - ObjC compatibility
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); }
}
|
apache-2.0
|
2b0381c722b934ea0790ecac4db01247
| 26.004215 | 169 | 0.478909 | 5.190804 | false | false | false | false |
twostraws/HackingWithSwift
|
Classic/project2/Project2/ViewController.swift
|
1
|
1618
|
//
// ViewController.swift
// Project2
//
// Created by TwoStraws on 13/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
@IBOutlet var button3: UIButton!
var countries = [String]()
var correctAnswer = 0
var score = 0
override func viewDidLoad() {
super.viewDidLoad()
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
button1.layer.borderColor = UIColor.lightGray.cgColor
button2.layer.borderColor = UIColor.lightGray.cgColor
button3.layer.borderColor = UIColor.lightGray.cgColor
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
askQuestion()
}
func askQuestion(action: UIAlertAction! = nil) {
countries.shuffle()
button1.setImage(UIImage(named: countries[0]), for: .normal)
button2.setImage(UIImage(named: countries[1]), for: .normal)
button3.setImage(UIImage(named: countries[2]), for: .normal)
correctAnswer = Int.random(in: 0...2)
title = countries[correctAnswer].uppercased()
}
@IBAction func buttonTapped(_ sender: UIButton) {
var title: String
if sender.tag == correctAnswer {
title = "Correct"
score += 1
} else {
title = "Wrong"
score -= 1
}
let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
present(ac, animated: true)
}
}
|
unlicense
|
e1a42ffb0f43aabbca4ef40f824d89f7
| 25.080645 | 129 | 0.697588 | 3.418605 | false | false | false | false |
Kara-wan/HandyNoti
|
HandyNoti/Classes/HandyNoti.swift
|
1
|
3290
|
import Foundation
/// 缓存池
fileprivate var NotiPool:[NSObject:[String:Selector]] = [:]
extension NotificationCenter {
/// 增加Handy观察者
///
/// - Parameters:
/// - observer: 观察者
/// - aSelector: 回调方法
/// - aName: 通知的名字
/// - anObject: 回调数据
open func addHandyObserver(_ observer: NSObject, selector aSelector: Selector, name aName: String, object anObject: Any?){
guard !checkOutNotiPool(observer ,aName, newSel: aSelector) else {
return
}
registerNoti(observer, selector: aSelector, name: aName, object: anObject)
}
/// 增加Handy观察者
///
/// - Parameter observer: 观察者
open func removeHandyObserver(_ observer: NSObject){
guard NotiPool[observer] != nil else {
return
}
NotiPool.removeValue(forKey: observer)
NotificationCenter.default.removeObserver(observer)
}
/// 移除观察者
///
/// - Parameters:
/// - observer: 观察者
/// - aName: 通知名称
/// - anObject: 回调数据
open func removeHandyObserver(_ observer: NSObject, name aName: String, object anObject: Any?){
guard NotiPool[observer] != nil else {
return
}
guard NotiPool[observer]![aName] != nil else {
return
}
NotiPool[observer]!.removeValue(forKey: aName)
removeObserver(observer, name: NSNotification.Name(rawValue: aName), object: anObject)
}
/// 校验是否注册了通知
///
/// - Parameters:
/// - observer: 观察者
/// - name: 通知名字
/// - Returns: 是否注册
open func didRegisted(_ observer:NSObject , _ name:String)->Bool{
guard NotiPool[observer] != nil else {
return false
}
return NotiPool[observer]![name] != nil
}
/// 注册通知
///
/// - Parameters:
/// - observer: 观察者
/// - aSelector: 回调方法
/// - aName: 通知名称
/// - anObject: 回调数据
fileprivate final func registerNoti(_ observer: NSObject, selector aSelector: Selector, name aName: String, object anObject: Any?){
var subPool:[String:Selector] = NotiPool[observer] ?? [:]
subPool[aName] = aSelector
NotiPool[observer] = subPool
self.addObserver(observer, selector: aSelector, name: Notification.Name(rawValue: aName), object: anObject)
}
/// 1.检查缓存池中是否存在该观察者,
/// 2.该观察者是否已经注册了通知(正常情况下是1的充要条件)
/// 2.已经监听的通知回调方法和新方法一致?
///
/// - Parameters:
/// - observer: 观察者
/// - notiName: 通知名称
/// - newSel: 新的回调方法
/// - Returns: 检查结果
fileprivate final func checkOutNotiPool(_ observer: NSObject , _ notiName:String,newSel:Selector)->Bool{
if let subPool:[String:Selector] = NotiPool[observer] {
if let sel:Selector = subPool[notiName] {
return sel == newSel
}
return false
}
return false
}
}
|
mit
|
81db4bffa1e62ec2223e35f067672c16
| 26.738318 | 135 | 0.563679 | 4.032609 | false | false | false | false |
ken0nek/swift
|
stdlib/public/core/StringBuffer.swift
|
1
|
8216
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_versioned
struct _StringBufferIVars {
internal init(_elementWidth: Int) {
_sanityCheck(_elementWidth == 1 || _elementWidth == 2)
usedEnd = nil
capacityAndElementShift = _elementWidth - 1
}
internal init(
_usedEnd: UnsafeMutablePointer<_RawByte>,
byteCapacity: Int,
elementWidth: Int
) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck((byteCapacity & 0x1) == 0)
self.usedEnd = _usedEnd
self.capacityAndElementShift = byteCapacity + (elementWidth - 1)
}
// This stored property should be stored at offset zero. We perform atomic
// operations on it using _HeapBuffer's pointer.
var usedEnd: UnsafeMutablePointer<_RawByte>?
var capacityAndElementShift: Int
var byteCapacity: Int {
return capacityAndElementShift & ~0x1
}
var elementShift: Int {
return capacityAndElementShift & 0x1
}
}
// FIXME: Wanted this to be a subclass of
// _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit>, but
// <rdar://problem/15520519> (Can't call static method of derived
// class of generic class with dependent argument type) prevents it.
public struct _StringBuffer {
// Make this a buffer of UTF-16 code units so that it's properly
// aligned for them if that's what we store.
typealias _Storage = _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit>
typealias HeapBufferStorage
= _HeapBufferStorage<_StringBufferIVars, UTF16.CodeUnit>
init(_ storage: _Storage) {
_storage = storage
}
public init(capacity: Int, initialSize: Int, elementWidth: Int) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck(initialSize <= capacity)
// We don't check for elementWidth overflow and underflow because
// elementWidth is known to be 1 or 2.
let elementShift = elementWidth &- 1
// We need at least 1 extra byte if we're storing 8-bit elements,
// because indexing will always grab 2 consecutive bytes at a
// time.
let capacityBump = 1 &- elementShift
// Used to round capacity up to nearest multiple of 16 bits, the
// element size of our storage.
let divRound = 1 &- elementShift
_storage = _Storage(
HeapBufferStorage.self,
_StringBufferIVars(_elementWidth: elementWidth),
(capacity + capacityBump + divRound) >> divRound
)
self.usedEnd = start + (initialSize << elementShift)
_storage.value.capacityAndElementShift
= ((_storage._capacity() - capacityBump) << 1) + elementShift
}
static func fromCodeUnits<
Input : Collection, // Sequence?
Encoding : UnicodeCodec
where Input.Iterator.Element == Encoding.CodeUnit
>(
_ input: Input, encoding: Encoding.Type, repairIllFormedSequences: Bool,
minimumCapacity: Int = 0
) -> (_StringBuffer?, hadError: Bool) {
// Determine how many UTF-16 code units we'll need
let inputStream = input.makeIterator()
guard let (utf16Count, isAscii) = UTF16.transcodedLength(
of: inputStream,
decodedAs: encoding,
repairingIllFormedSequences: repairIllFormedSequences) else {
return (nil, true)
}
// Allocate storage
let result = _StringBuffer(
capacity: max(utf16Count, minimumCapacity),
initialSize: utf16Count,
elementWidth: isAscii ? 1 : 2)
if isAscii {
var p = UnsafeMutablePointer<UTF8.CodeUnit>(result.start)
let sink: (UTF32.CodeUnit) -> Void = {
p.pointee = UTF8.CodeUnit($0)
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF32.self,
stoppingOnError: true,
sendingOutputTo: sink)
_sanityCheck(!hadError, "string cannot be ASCII if there were decoding errors")
return (result, hadError)
}
else {
var p = result._storage.baseAddress
let sink: (UTF16.CodeUnit) -> Void = {
p.pointee = $0
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF16.self,
stoppingOnError: !repairIllFormedSequences,
sendingOutputTo: sink)
return (result, hadError)
}
}
/// A pointer to the start of this buffer's data area.
public // @testable
var start: UnsafeMutablePointer<_RawByte> {
return UnsafeMutablePointer(_storage.baseAddress)
}
/// A past-the-end pointer for this buffer's stored data.
var usedEnd: UnsafeMutablePointer<_RawByte> {
get {
return _storage.value.usedEnd!
}
set(newValue) {
_storage.value.usedEnd = newValue
}
}
var usedCount: Int {
return (usedEnd - start) >> elementShift
}
/// A past-the-end pointer for this buffer's available storage.
var capacityEnd: UnsafeMutablePointer<_RawByte> {
return start + _storage.value.byteCapacity
}
/// The number of elements that can be stored in this buffer.
public var capacity: Int {
return _storage.value.byteCapacity >> elementShift
}
/// 1 if the buffer stores UTF-16; 0 otherwise.
var elementShift: Int {
return _storage.value.elementShift
}
/// The number of bytes per element.
var elementWidth: Int {
return elementShift + 1
}
// Return `true` iff we have the given capacity for the indicated
// substring. This is what we need to do so that users can call
// reserveCapacity on String and subsequently use that capacity, in
// two separate phases. Operations with one-phase growth should use
// "grow()," below.
func hasCapacity(
_ cap: Int, forSubRange r: Range<UnsafePointer<_RawByte>>
) -> Bool {
// The substring to be grown could be pointing in the middle of this
// _StringBuffer.
let offset = (r.lowerBound - UnsafePointer(start)) >> elementShift
return cap + offset <= capacity
}
/// Attempt to claim unused capacity in the buffer.
///
/// Operation succeeds if there is sufficient capacity, and either:
/// - the buffer is uniquely-referenced, or
/// - `oldUsedEnd` points to the end of the currently used capacity.
///
/// - parameter bounds: Range of the substring that the caller tries
/// to extend.
/// - parameter newUsedCount: The desired size of the substring.
@inline(__always)
@discardableResult
mutating func grow(
oldBounds bounds: Range<UnsafePointer<_RawByte>>, newUsedCount: Int
) -> Bool {
var newUsedCount = newUsedCount
// The substring to be grown could be pointing in the middle of this
// _StringBuffer. Adjust the size so that it covers the imaginary
// substring from the start of the buffer to `oldUsedEnd`.
newUsedCount += (bounds.lowerBound - UnsafePointer(start)) >> elementShift
if _slowPath(newUsedCount > capacity) {
return false
}
let newUsedEnd = start + (newUsedCount << elementShift)
if _fastPath(self._storage.isUniquelyReferenced()) {
usedEnd = newUsedEnd
return true
}
// Optimization: even if the buffer is shared, but the substring we are
// trying to grow is located at the end of the buffer, it can be grown in
// place. The operation should be implemented in a thread-safe way,
// though.
//
// if usedEnd == bounds.upperBound {
// usedEnd = newUsedEnd
// return true
// }
let usedEndPhysicalPtr =
UnsafeMutablePointer<UnsafeMutablePointer<_RawByte>>(_storage._value)
var expected = UnsafeMutablePointer<_RawByte>(bounds.upperBound)
if _stdlib_atomicCompareExchangeStrongPtr(
object: usedEndPhysicalPtr, expected: &expected, desired: newUsedEnd) {
return true
}
return false
}
var _anyObject: AnyObject? {
return _storage.storage != nil ? _storage.storage! : nil
}
var _storage: _Storage
}
|
apache-2.0
|
b8f2a9841b7af55151fad7df9b99bf82
| 31.995984 | 85 | 0.663096 | 4.541736 | false | false | false | false |
nicksnyder/ios-cell-layout
|
CellLayout/UIDeviceExtension.swift
|
1
|
720
|
//
// Created by Nick Snyder on 6/12/15.
// Copyright (c) 2015 Example. All rights reserved.
//
import UIKit
extension UIDevice {
class func hasMinimumSystemVersion(version: String) -> Bool {
let systemVersion = UIDevice.currentDevice().systemVersion
let compareResult = systemVersion.compare(version, options: .NumericSearch)
return compareResult == .OrderedSame || compareResult == .OrderedDescending
}
class func hasMajorSystemVersion(version: Int) -> Bool {
let systemVersion = UIDevice.currentDevice().systemVersion
if let majorVersion = systemVersion.substringToIndex(advance(systemVersion.startIndex, 1)).toInt() {
return version == majorVersion
}
return false
}
}
|
mit
|
958ad93d7e443ba10280aab7e5b2e806
| 31.772727 | 104 | 0.730556 | 4.736842 | false | false | false | false |
BareFeetWare/BFWControls
|
BFWControls/Modules/Layout/View/UIView+NSLayoutConstraints.swift
|
1
|
6083
|
//
// UIView+NSLayoutConstraints.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 11/02/2016.
// Copyright © 2018 BareFeetWare. All rights reserved.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
public extension UIView {
func pinToSuperviewEdges() {
pin(to: superview!,
attributes: [.left, .right, .top, .bottom],
secondAttributes: [.left, .right, .top, .bottom]
)
}
func pinToSuperviewMargins() {
pin(to: superview!,
attributes: [.left, .right, .top, .bottom],
secondAttributes: [.leftMargin, .rightMargin, .topMargin, .bottomMargin]
)
}
func pinToSuperview(with inset: CGFloat) {
pin(to: superview!,
attributes: [.left, .right, .top, .bottom],
secondAttributes: [.left, .right, .top, .bottom],
constants: [inset, -inset, inset, -inset])
}
func pin(to view: UIView,
attributes: [NSLayoutConstraint.Attribute],
secondAttributes: [NSLayoutConstraint.Attribute],
constants: [CGFloat] = [0, 0, 0, 0])
{
var constraints = [NSLayoutConstraint]()
for attributeN in 0 ..< attributes.count {
let constraint = NSLayoutConstraint(
item: self,
attribute: attributes[attributeN],
relatedBy: .equal,
toItem: view,
attribute: secondAttributes[attributeN],
multiplier: 1.0,
constant: constants[attributeN]
)
constraints.append(constraint)
}
NSLayoutConstraint.activate(constraints)
translatesAutoresizingMaskIntoConstraints = false
}
func activateOnlyConstraintsWithFirstVisible(in views: [UIView]) {
var firstMatchedView: UIView?
for view in views {
let isFirstMatch = firstMatchedView == nil && !(view.isHidden)
if let constraints = constraints(with: view) {
if isFirstMatch {
firstMatchedView = view
NSLayoutConstraint.activate(constraints)
} else {
NSLayoutConstraint.deactivate(constraints)
}
}
}
}
func constraints(with view: UIView) -> [NSLayoutConstraint]? {
return commonAncestor(with: view)?.constraints.filter { constraint in
constraint.isBetween(item: self, otherItem: view)
}
}
var siblingAndSuperviewConstraints: [NSLayoutConstraint]? {
return superview?.constraints.filter { constraint in
var include = false
if let firstItem = constraint.firstItem as? NSObject,
let secondItem = constraint.secondItem as? NSObject,
firstItem == self || secondItem == self
{
include = true
}
return include
}
}
func deactivateConstraintsIfHidden() {
if let siblingAndSuperviewConstraints = siblingAndSuperviewConstraints {
if isHidden {
NSLayoutConstraint.deactivate(siblingAndSuperviewConstraints)
} else {
NSLayoutConstraint.activate(siblingAndSuperviewConstraints)
}
}
}
func addConstraint(toBypass sibling: UIView) {
if let superview = superview,
superview == sibling.superview,
let gapConstraint: NSLayoutConstraint = sibling
.constraints(with: self)?
.first( where: {
[.left, .leftMargin, .leading, .leadingMargin, .top, .topMargin]
.contains($0.attribute(for: sibling)!)
&& [.right, .rightMargin, .trailing, .trailingMargin, .bottom, .bottomMargin]
.contains($0.attribute(for: self)!)
} ),
let siblingToSuperConstraint: NSLayoutConstraint = sibling
// TODO: Also handle if constraint with superview's safe area.
.constraints(with: superview)?
.first( where: {
gapConstraint.attribute(for: self)! == $0.attribute(for: $0.otherItem(if: sibling)!)!
})
{
let selfToSuperConstraint = siblingToSuperConstraint.constraint(
byReplacing: [sibling],
with: [self])
superview.addConstraint(selfToSuperConstraint)
sibling.isHidden = true
sibling.deactivateConstraintsIfHidden()
}
}
var widthMultiplier: CGFloat? {
get {
return widthConstraint?.multiplier
}
set {
if let widthConstraint = widthConstraint {
if let width = newValue {
let newConstraint = widthConstraint.constraint(with: width)
superview!.removeConstraint(widthConstraint)
superview!.addConstraint(newConstraint)
}
}
}
}
var widthConstraint: NSLayoutConstraint? {
get {
var widthConstraint: NSLayoutConstraint?
if let superview = superview {
for constraint in superview.constraints {
if let firstItem = constraint.firstItem as? UIView,
let secondItem = constraint.secondItem as? UIView
{
if [firstItem, secondItem].contains(self)
&& [firstItem, secondItem].contains(superview)
&& constraint.firstAttribute == .width
&& constraint.secondAttribute == .width
{
widthConstraint = constraint
break
}
}
}
}
return widthConstraint
}
}
}
|
mit
|
da4738572a4d866d143b29e198433ce0
| 35.638554 | 105 | 0.535186 | 5.700094 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
Courses/stanford/stanford/cs193p/2015/SmashTag/SmashTag/Tweet.swift
|
3
|
6994
|
//
// Tweet.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import Foundation
// a simple container class which just holds the data in a Tweet
// IndexedKeywords are substrings of the Tweet's text
// for example, a hashtag or other user or url that is mentioned in the Tweet
// note carefully the comments on the two range properties in an IndexedKeyword
// Tweet instances re created by fetching from Twitter using a TwitterRequest
public class Tweet : Printable
{
public let text: String
public let user: User
public let created: NSDate
public let id: String?
public let media = [MediaItem]()
public let hashtags = [IndexedKeyword]()
public let urls = [IndexedKeyword]()
public let userMentions = [IndexedKeyword]()
public struct IndexedKeyword: Printable
{
public let keyword: String // will include # or @ or http:// prefix
public let range: Range<String.Index> // index into the Tweet's text property only
public let nsrange: NSRange // index into an NS[Attributed]String made from the Tweet's text
public init?(data: NSDictionary?, inText: String, prefix: String?) {
let indices = data?.valueForKeyPath(TwitterKey.Entities.Indices) as? NSArray
if let startIndex = (indices?.firstObject as? NSNumber)?.integerValue {
if let endIndex = (indices?.lastObject as? NSNumber)?.integerValue {
let length = count(inText)
if length > 0 {
let start = max(min(startIndex, length-1), 0)
let end = max(min(endIndex, length), 0)
if end > start {
range = advance(inText.startIndex, start)...advance(inText.startIndex, end-1)
keyword = inText.substringWithRange(range)
if prefix != nil && !keyword.hasPrefix(prefix!) && start > 0 {
range = advance(inText.startIndex, start-1)...advance(inText.startIndex, end-2)
keyword = inText.substringWithRange(range)
}
if prefix == nil || keyword.hasPrefix(prefix!) {
nsrange = inText.rangeOfString(keyword, nearRange: NSMakeRange(startIndex, endIndex-startIndex))
if nsrange.location != NSNotFound {
return
}
}
}
}
}
}
return nil
}
public var description: String { get { return "\(keyword) (\(nsrange.location), \(nsrange.location+nsrange.length-1))" } }
}
public var description: String { return "\(user) - \(created)\n\(text)\nhashtags: \(hashtags)\nurls: \(urls)\nuser_mentions: \(userMentions)" + (id == nil ? "" : "\nid: \(id!)") }
// MARK: - Private Implementation
init?(data: NSDictionary?) {
if let user = User(data: data?.valueForKeyPath(TwitterKey.User) as? NSDictionary) {
self.user = user
if let text = data?.valueForKeyPath(TwitterKey.Text) as? String {
self.text = text
if let created = (data?.valueForKeyPath(TwitterKey.Created) as? String)?.asTwitterDate {
self.created = created
id = data?.valueForKeyPath(TwitterKey.ID) as? String
if let mediaEntities = data?.valueForKeyPath(TwitterKey.Media) as? NSArray {
for mediaData in mediaEntities {
if let mediaItem = MediaItem(data: mediaData as? NSDictionary) {
media.append(mediaItem)
}
}
}
let hashtagMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.Hashtags) as? NSArray
hashtags = getIndexedKeywords(hashtagMentionsArray, inText: text, prefix: "#")
let urlMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.URLs) as? NSArray
urls = getIndexedKeywords(urlMentionsArray, inText: text, prefix: "h")
let userMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.UserMentions) as? NSArray
userMentions = getIndexedKeywords(userMentionsArray, inText: text, prefix: "@")
return
}
}
}
// we've failed
// but compiler won't let us out of here with non-optional values unset
// so set them to anything just to able to return nil
// we could make these implicitly-unwrapped optionals, but they should never be nil, ever
self.text = ""
self.user = User()
self.created = NSDate()
return nil
}
private func getIndexedKeywords(dictionary: NSArray?, inText: String, prefix: String? = nil) -> [IndexedKeyword] {
var results = [IndexedKeyword]()
if let indexedKeywords = dictionary {
for indexedKeywordData in indexedKeywords {
if let indexedKeyword = IndexedKeyword(data: indexedKeywordData as? NSDictionary, inText: inText, prefix: prefix) {
results.append(indexedKeyword)
}
}
}
return results
}
struct TwitterKey {
static let User = "user"
static let Text = "text"
static let Created = "created_at"
static let ID = "id_str"
static let Media = "entities.media"
struct Entities {
static let Hashtags = "entities.hashtags"
static let URLs = "entities.urls"
static let UserMentions = "entities.user_mentions"
static let Indices = "indices"
}
}
}
private extension NSString {
func rangeOfString(substring: NSString, nearRange: NSRange) -> NSRange {
var start = max(min(nearRange.location, length-1), 0)
var end = max(min(nearRange.location + nearRange.length, length), 0)
var done = false
while !done {
let range = rangeOfString(substring as String, options: NSStringCompareOptions.allZeros, range: NSMakeRange(start, end-start))
if range.location != NSNotFound {
return range
}
done = true
if start > 0 { start-- ; done = false }
if end < length { end++ ; done = false }
}
return NSMakeRange(NSNotFound, 0)
}
}
private extension String {
var asTwitterDate: NSDate? {
get {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
return dateFormatter.dateFromString(self)
}
}
}
|
mit
|
8c218efad9297d6b1680b80932f3ddf7
| 43.547771 | 183 | 0.566343 | 5.01362 | false | false | false | false |
IamAlchemist/DemoAnimations
|
Animations/ImageExplosionViewController.swift
|
2
|
2984
|
//
// ImageExplosionViewController.swift
// DemoAnimations
//
// Created by wizard lee on 7/25/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
class ImageExplosionViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var imageView: UIImageView!
let distanceRange: CGFloat = 200;
var myLayer = CALayer()
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: "john-paulson")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myLayer.backgroundColor = UIColor.orangeColor().CGColor
myLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
imageView.layer.addSublayer(myLayer)
var perspective = CATransform3DIdentity
perspective.m34 = -1/500.0
imageView.layer.sublayerTransform = perspective
myLayer.position = imageView.center
}
@IBAction func animate(sender: UIButton) {
let rotate = (CGFloat(arc4random_uniform(360)) - 180)/180.0
let distanceX = (CGFloat(arc4random_uniform(100)) - 50)/50.0
let distanceY = (CGFloat(arc4random_uniform(100)) - 50)/50.0
print("\(rotate), \(distanceX), \(distanceY)")
animateWithLayer(myLayer, rotate: rotate, distance: CGPoint(x: distanceX, y: distanceY), duration: 2)
}
func animateWithLayer(layer:CALayer, rotate: CGFloat, distance: CGPoint, duration: CFTimeInterval) {
let animation = CABasicAnimation()
let fromTransform = CATransform3DIdentity
var toTransform = CATransform3DIdentity
let rotateDegree = rotate * CGFloat(M_PI)
toTransform = CATransform3DTranslate(toTransform, 0, 0, -1000)
toTransform = CATransform3DRotate(toTransform, rotateDegree, 0, 0, 1)
animation.keyPath = "transform"
animation.fromValue = NSValue(CATransform3D: fromTransform)
animation.toValue = NSValue(CATransform3D: toTransform)
let animation2 = CABasicAnimation()
let originalPosition = myLayer.position
let toPosition = CGPoint(x: originalPosition.x + distance.x * distanceRange,
y: originalPosition.y + distance.y * distanceRange)
animation2.keyPath = "position"
animation2.toValue = NSValue(CGPoint: toPosition)
let animation3 = CABasicAnimation()
animation3.keyPath = "opacity"
animation3.toValue = NSNumber(float: 0)
let animationGroups = CAAnimationGroup()
animationGroups.animations = [animation, animation2, animation3]
animationGroups.duration = duration
animationGroups.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
myLayer.addAnimation(animationGroups, forKey: nil)
}
}
|
mit
|
4ce7bad3e6b61878f70c824d827fb85e
| 35.378049 | 109 | 0.649346 | 4.819063 | false | false | false | false |
v2panda/DaysofSwift
|
GoodAsOldPhones/GoodAsOldPhones/ProductsTableViewController.swift
|
1
|
2145
|
//
// ProductsTableViewController.swift
// GoodAsOldPhones
//
// Created by v2panda on 2017/2/25.
// Copyright © 2017年 Panda. All rights reserved.
//
import UIKit
class ProductsTableViewController: UITableViewController {
var products: [Product]?
override func viewDidLoad() {
super.viewDidLoad()
products = [Product(name: "1907 Wall Set", cellImageName: "image-cell1", fullscreenImageName: "phone-fullscreen1"),
Product(name: "1921 Dial Phone", cellImageName: "image-cell2", fullscreenImageName: "phone-fullscreen2"),
Product(name: "1937 Desk Set", cellImageName: "image-cell3", fullscreenImageName: "phone-fullscreen3"),
Product(name: "1984 Moto Portable", cellImageName: "image-cell4", fullscreenImageName: "phone-fullscreen4")]
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let products = products {
return products.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "productCell", for: indexPath)
cell.textLabel?.text = products?[indexPath.row].name
if let imageName = products?[indexPath.row].cellImageName {
cell.imageView?.image = UIImage(named: imageName)
}
return cell
}
// 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?) {
if segue.identifier == "showProduct" {
let productVC = segue.destination as? ProductViewController
if let cell = sender as? UITableViewCell {
if let IndexPath = tableView.indexPath(for: cell) {
productVC?.product = products?[IndexPath.row]
}
}
}
}
}
|
mit
|
4529607ba960d95786e567528889b0f7
| 30.5 | 128 | 0.625584 | 4.912844 | false | false | false | false |
cyhuang1230/CYHPOPImageButton
|
Pod/Classes/CYHPOPImageButton.swift
|
1
|
1827
|
//
// CYHPOPImageButton.swift
// CYHPOPImageButton
//
// Created by Chien-Yu Huang on 8/11/15.
// Copyright © 2015 Chien-Yu Huang. All rights reserved.
//
import UIKit
import pop
public class CYHPOPImageButton: UIButton {
let NAME_SHRINK_ANIMATION = "CYHPOPImageButton_animation_SHRINK";
let NAME_ENLARGE_ANIMATION = "CYHPOPImageButton_animation_ENLARGE";
public init(image: UIImage) {
super.init(frame: CGRectMake(0, 0, image.size.width, image.size.height));
self.setImage(image, forState: .Normal);
self.adjustsImageWhenHighlighted = false;
NSLog("CYHPOPImageButton init with image: \(image)");
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
assertionFailure("CYHPOPImageButton init with coder");
}
override public var highlighted: Bool {
willSet {
if newValue && !highlighted {
if self.pop_animationForKey(NAME_ENLARGE_ANIMATION) != nil {
self.pop_removeAnimationForKey(NAME_ENLARGE_ANIMATION);
}
self.shrinkButton();
} else if !newValue {
if self.pop_animationForKey(NAME_SHRINK_ANIMATION) != nil {
self.pop_removeAnimationForKey(NAME_SHRINK_ANIMATION);
}
self.enlargeButton();
}
}
}
private func shrinkButton() {
let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewScaleXY);
animation.springBounciness = 20;
animation.toValue = NSValue(CGSize: CGSizeMake(0.8, 0.8));
self.pop_addAnimation(animation, forKey: NAME_SHRINK_ANIMATION);
}
private func enlargeButton() {
let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewScaleXY);
animation.springBounciness = 20;
animation.toValue = NSValue(CGSize: CGSizeMake(1, 1));
self.pop_addAnimation(animation, forKey: NAME_ENLARGE_ANIMATION);
}
}
|
mit
|
eb614fcb6781ad9df6b184bba5d8738d
| 25.1 | 89 | 0.714129 | 3.545631 | false | false | false | false |
iscriptology/swamp
|
Swamp/Messages/PubSub/Subscriber/SubscribeSwampMessage.swift
|
2
|
831
|
//
// SubscribeSwampMessage.swift
// Pods
//
// Created by Yossi Abraham on 24/08/2016.
//
//
import Foundation
/// [SUBSCRIBE, requestId|number, options|dict, topic|string]
class SubscribeSwampMessage: SwampMessage {
let requestId: Int
let options: [String: Any]
let topic: String
init(requestId: Int, options: [String: Any], topic: String) {
self.requestId = requestId
self.options = options
self.topic = topic
}
// MARK: SwampMessage protocol
required init(payload: [Any]) {
self.requestId = payload[0] as! Int
self.options = payload[1] as! [String: Any]
self.topic = payload[2] as! String
}
func marshal() -> [Any] {
return [SwampMessages.subscribe.rawValue, self.requestId, self.options, self.topic]
}
}
|
mit
|
b849639db381e0cfcd1b3919be140d2d
| 23.441176 | 91 | 0.620939 | 3.777273 | false | false | false | false |
minsOne/DigitClockInSwift
|
MainFeature/MainFeature/Dependencies/Settings/Settings/Sources/ViewController.swift
|
1
|
3592
|
//
// ViewController.swift
// Settings
//
// Created by minsone on 2019/10/19.
// Copyright © 2019 minsone. All rights reserved.
//
import Foundation
import RIBs
import RxSwift
import UIKit
import Library
public protocol PresentableListener: class {
func update(color: UIColor)
func done()
}
final public class ViewController: UITableViewController, SettingTableViewCellPresenterListener, Instantiable, Presentable, ViewControllable {
public static var storyboardName: String { "SettingsViewController" }
// MARK: Properties
var btnDone: UIBarButtonItem?
private let headerTitleList = ["Theme", "Maker", "Version"]
private let makerTexts = ["Developer : Ahn Jung Min",
"Designer : Joo Sung Hyun"]
public weak var listener: PresentableListener?
override public var prefersStatusBarHidden: Bool { true }
override public func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
self.title = "Digit Clock"
self.initBarButton()
}
func initBarButton() {
guard responds(to: #selector(pressedDoneBtn))
else { return }
btnDone = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(pressedDoneBtn))
navigationItem.setRightBarButton(btnDone, animated: true)
}
override public func numberOfSections(in tableView: UITableView) -> Int { 3 }
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 1: return makerTexts.count
default: return 1
}
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: SettingTableViewCell
switch indexPath.section {
case 1:
cell = tableView.dequeueReusableCell(withIdentifier: makerCellIdentifier,
for: indexPath)
as! SettingMakerTableViewCell
let makerCell = cell as! SettingMakerTableViewCell
makerCell.makerLabel.text = makerTexts[indexPath.row]
case 2:
cell = tableView.dequeueReusableCell(
withIdentifier: versionCellIdentifier,
for: indexPath)
as! SettingVersionTableViewCell
let versionCell = cell as! SettingVersionTableViewCell
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
versionCell.versionLabel.text = "Version : " + version
default:
cell = tableView.dequeueReusableCell(withIdentifier: themeCellIdentifier, for: indexPath)
as! SettingThemeTableViewCell
}
cell.selectionStyle = .none
cell.delegate = self
return cell
}
override public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
headerTitleList[section]
}
override public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
@objc func pressedDoneBtn(sender: UIBarButtonItem) {
listener?.done()
}
func selectedBackground(theme: UIColor) {
listener?.update(color: theme)
if !UIDevice.isIPad {
listener?.done()
}
}
}
|
mit
|
7fe000adc0fd8f2691a9f85275eb0313
| 29.956897 | 142 | 0.620162 | 5.465753 | false | false | false | false |
kingcos/CS193P_2017
|
CalculatorPlayground.playground/Contents.swift
|
1
|
293
|
//: Playground - noun: a place where people can play
import UIKit
let i = 27
// 函数在 Swift 中也是类型
var f: (Double) -> Double
f = sqrt
let x = f(81)
f = cos
let y = f(Double.pi)
func changeSign(operand: Double) -> Double {
return -operand
}
f = changeSign
let z = f(81)
|
mit
|
baac2e42aa1d1cac0309a4e9814dde8f
| 12.190476 | 52 | 0.638989 | 2.742574 | false | false | false | false |
halo/LinkLiar
|
LinkLiarTests/JSONWriterTests.swift
|
1
|
1995
|
/*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import XCTest
@testable import LinkLiar
class JSONWriterTests: XCTestCase {
func tempPath(_ fileName: String) -> String {
let directory = NSTemporaryDirectory()
return URL(fileURLWithPath: directory, isDirectory: true).appendingPathComponent(fileName).path
}
func testWriteWithEmptyDictionary() {
let path = tempPath("empty.json")
let dictionary = [String: Any]()
JSONWriter(filePath: path).write(dictionary)
let json = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
XCTAssertEqual("{\n\n}", json)
}
func testWriteWithVersion() {
let path = tempPath("empty.json")
let dictionary = ["version": "42"]
JSONWriter(filePath: path).write(dictionary)
let json = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
XCTAssertEqual("{\n \"version\" : \"42\"\n}", json)
}
}
|
mit
|
541003d544a31b44bb7954db09d98fe5
| 45.395349 | 133 | 0.740351 | 4.403974 | false | true | false | false |
blackmirror-media/BMPickerModal
|
BMPickerModal/Classes/BMPickerModal.swift
|
1
|
7530
|
//
// BMDatePickerModal.swift
//
//
// Created by Adam Eri on 17/11/2014.
// Copyright (c) blackmirror media.
//
import Foundation
import UIKit
@objc public enum BMPickerModalMode: Int {
case datePicker
case picker
}
public class BMPickerModal:
UIViewController,
UIPopoverPresentationControllerDelegate,
UIPickerViewDataSource,
UIPickerViewDelegate {
/// Closure to be executed when new date is selected
public var onSelection: ((AnyObject) -> Void)?
/// True if the picker is inside a popover. iPad only.
public var shownInPopover: Bool = false
/// True if the modal is currently visible
public var isVisible: Bool = false
/// Mode of the picker. DatePicker or simple Picker
@objc public var mode: BMPickerModalMode = .datePicker
/// The DatePicker itself
@objc public var datePicker: UIDatePicker = UIDatePicker()
/// The Picker itself
public var picker: UIPickerView = UIPickerView()
/// Data Source of te Picker. Array of elements
public var pickerDataSource: NSArray?
/// Index of the selected picker value
private var selectedPickerValueIndex: Int = 0
/// Text for save button
public var saveButtonTitle: String = "Save"
public var cancelButtonTitle: String = "Cancel"
/// Blur effect style of the modal. ExtraLight by default
public var blurEffectStyle: UIBlurEffectStyle = .extraLight
/// Blur view
private var blurEffectView: UIVisualEffectView!
private let window: UIWindow = UIApplication.shared.windows[0]
/// Size of the popover on the iPad
private let popoverSize: CGSize = CGSize(width: 460, height: 261)
// MARK: View Life Cycle
override public func viewDidLoad() {
super.viewDidLoad()
self.blurEffectView = UIVisualEffectView(
effect: UIBlurEffect(style: self.blurEffectStyle))
self.blurEffectView.frame = self.view.frame
var pickerSize = self.window.frame.size
if UIDevice.current.userInterfaceIdiom == .pad {
pickerSize = self.popoverSize
}
self.view.frame = CGRect(
x: 0,
y: pickerSize.height - 260,
width: pickerSize.width,
height: 260)
self.blurEffectView.frame = CGRect(
x: 0,
y: 0,
width: self.view.frame.size.width,
height: self.view.frame.size.height);
if self.mode == .datePicker {
self.datePicker.frame = CGRect(
x: 0,
y: 30,
width: pickerSize.width,
height: 260);
self.blurEffectView.contentView.addSubview(self.datePicker)
}
else if self.mode == .picker {
self.picker.frame = CGRect(
x: 0,
y: 30,
width: pickerSize.width,
height: 260);
self.picker.dataSource = self;
self.picker.delegate = self;
self.blurEffectView.contentView.addSubview(self.picker)
}
self.view.addSubview(blurEffectView)
}
override public func viewDidDisappear(_ animated: Bool) {
self.shownInPopover = false
self.isVisible = false
super.viewDidDisappear(animated)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.isVisible = true
let cancelButton: UIButton = UIButton(type: UIButtonType.system)
cancelButton.setTitle(self.cancelButtonTitle, for: UIControlState())
cancelButton.frame = CGRect(x: 5, y: 5, width: 100, height: 30);
cancelButton.titleLabel?.textAlignment = NSTextAlignment.left;
cancelButton.addTarget(
self,
action: #selector(dismiss as () -> Void),
for: UIControlEvents.touchUpInside);
if self.blurEffectStyle == .dark {
cancelButton.setTitleColor(UIColor.black, for: UIControlState())
}
self.blurEffectView.contentView.addSubview(cancelButton)
let saveButton: UIButton = UIButton(type: UIButtonType.system)
saveButton.setTitle(self.saveButtonTitle, for: UIControlState())
saveButton.frame = CGRect(
x: self.view.frame.size.width - 90,
y: 5,
width: 100,
height: 30);
saveButton.titleLabel?.textAlignment = .right;
saveButton.addTarget(self, action: #selector(save), for: .touchUpInside)
if self.blurEffectStyle == .dark {
saveButton.setTitleColor(UIColor.black, for: UIControlState())
}
self.blurEffectView.contentView.addSubview(saveButton)
}
// MARK: User Actions
/**
Saving the value selected. Triggers the onSelection closure
*/
@objc public func save() {
if self.onSelection != nil {
if self.mode == .datePicker {
self.onSelection!(self.datePicker.date as AnyObject)
}
else if self.mode == .picker {
self.onSelection!(self.selectedPickerValueIndex as AnyObject)
}
}
self.dismiss()
}
/**
Opens the date picker modal
*/
@objc public func show () {
self.show(nil)
}
/**
Shows the date picker modal in a popover controller and sets the
completion block.
- parameter selection: Closure to be executed when date/data is selectes
- parameter sourceView: view to show from
- parameter sourceRect: rect to align to
- parameter inViewController: viewController used to present the modal
*/
@objc public func showInPopover (
_ selection: ((AnyObject) -> Void)?,
sourceView: UIView,
sourceRect: CGRect,
inViewController: UIViewController?) {
self.shownInPopover = true
self.onSelection = selection
self.modalPresentationStyle = .popover
self.preferredContentSize = self.popoverSize
var viewController: UIViewController? = inViewController
if viewController == nil {
viewController = self.window.rootViewController!
}
let popover = self.popoverPresentationController
popover?.delegate = self
popover?.sourceView = sourceView
popover?.sourceRect = sourceRect
viewController!.present(self, animated: true, completion: { () -> Void in
// nothing here
})
}
/**
Shows the date picker modal and sets the completion block.
- parameter selection: closure to be executed when new date is selected
*/
@objc public func show (_ selection: ((AnyObject) -> Void)?) {
self.onSelection = selection
self.view.alpha = 0.0
self.window.addSubview(self.view)
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.alpha = 1.0;
})
}
/**
Closes the modal
*/
@objc public func dismiss() {
if self.shownInPopover {
self.shownInPopover = false
super.dismiss(animated: true, completion: nil)
}
else {
UIView.animate(withDuration: 0.3,
animations: { () -> Void in
self.view.alpha = 0.0;
}) { (completed) -> Void in
self.view.removeFromSuperview()
}
}
}
// MARK: Picker View Delegates
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(
_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return self.pickerDataSource?.count ?? 0
}
public func pickerView(
_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int) -> String? {
return self.pickerDataSource?.object(at: row) as! NSString as String
}
public func pickerView(
_ pickerView: UIPickerView,
didSelectRow row: Int,
inComponent component: Int) {
self.selectedPickerValueIndex = row
}
}
|
mit
|
bd6c9dab1bcfd234e70450392684e8fa
| 26.381818 | 79 | 0.66162 | 4.558111 | false | false | false | false |
JoeLago/MHGDB-iOS
|
MHGDB/Screens/Monster/MonsterList.swift
|
1
|
1350
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import UIKit
class MonsterList: DetailController {
var monsterSection: SimpleDetailSection<Monster>!
var segment: UISegmentedControl!
override func loadView() {
super.loadView()
title = "Monsters"
monsterSection = SimpleDetailSection(data: Database.shared.monsters(size: .large)) {
[unowned self] (model: Monster) in
self.push(MonsterDetails(id: model.id))
}
add(section: monsterSection)
segment = populateToolbarSegment(items: ["Large", "Small", "All"])
segment.selectedSegmentIndex = 0
isToolBarHidden = false;
}
var selectedSize: Monster.Size? {
get {
switch segment.selectedSegmentIndex {
case 0: return .large
case 1: return .small
default: return nil
}
}
}
var monsterSize: Monster.Size? {
didSet {
monsterSection.rows = Database.shared.monsters(size: monsterSize)
}
}
override func reloadData() {
monsterSize = selectedSize
tableView.reloadData()
}
}
extension Monster: DetailCellModel {
var primary: String? { return name }
var imageName: String? { return icon }
}
|
mit
|
a87f6bc04e5dcb5428c85b2c54166467
| 23.545455 | 92 | 0.583704 | 4.753521 | false | false | false | false |
sora0077/LayoutKit
|
LayoutKitDemo/TimelineRow.swift
|
1
|
629
|
//
// TimelineRow.swift
// LayoutKit
//
// Created by 林 達也 on 2015/01/22.
// Copyright (c) 2015年 林 達也. All rights reserved.
//
import UIKit
import LayoutKit
class TimelineRow<T: UITableViewCell where T: TableElementRendererProtocol>: TableRow<T> {
private let title: String
init(title: String = "") {
self.title = title
super.init()
}
override func viewWillAppear() {
if self.title == "10" {
self.separatorStyle = .None
}
}
override func viewDidLayoutSubviews() {
self.renderer?.textLabel?.text = "cell \(self.title)"
}
}
|
mit
|
e03b2081f49d98bf16cac8bba0a73230
| 17.636364 | 90 | 0.60813 | 3.917197 | false | false | false | false |
dreamsxin/swift
|
validation-test/compiler_crashers_fixed/01443-swift-lexer-leximpl.swift
|
11
|
766
|
// 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
: Any) {
class A : e)) -> {
enum S) -> S {
typealias B) {
func d>(self.g == a: T) {
protocol b = {
0.d() {
}
protocol b = c) -> T, A {
}
protocol P {
}
}
}
}
public subscript (h, b in a {
struct X.d {
}
extension A : b {
}
}
extension A {
case b = Swift.h: end: (Any, e = j> : Any] == {
}
}
let n1: String {
}
}
return {
return { x }
}
}
}
protocol c : Any, e {
func e> Boo
|
apache-2.0
|
11c42527251f65a8680190fa31705762
| 16.813953 | 78 | 0.627937 | 2.837037 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat.ShareExtension/State/ActionCreators/SelectServer.swift
|
1
|
1976
|
//
// SelectServer.swift
// Rocket.Chat.ShareExtension
//
// Created by Matheus Cardoso on 3/6/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
func fetchServers(store: SEStore) -> SEAction {
let servers = DatabaseManager.servers?.compactMap { dict -> SEServer? in
guard
let name = dict[ServerPersistKeys.serverName],
let host = URL(string: dict[ServerPersistKeys.serverURL] ?? "")?.httpServerURL()?.absoluteString,
let userId = dict[ServerPersistKeys.userId],
let token = dict[ServerPersistKeys.token],
let iconUrl = dict[ServerPersistKeys.serverIconURL]
else {
return nil
}
return SEServer(name: name, host: host, userId: userId, token: token, iconUrl: iconUrl)
} ?? []
return .setServers(servers)
}
func fetchRooms(store: SEStore) -> SEAction {
defer {
let request = SubscriptionsRequest(updatedSince: nil)
store.state.api?.fetch(request) { response in
switch response {
case .resource(let resource):
store.dispatch(.setRooms(resource.subscriptions ?? []))
case .error:
store.dispatch(.setRooms([]))
}
}
}
guard let realm = DatabaseManager.databaseInstace(index: store.state.selectedServerIndex) else {
return .setRooms([])
}
let rooms = Array(realm.objects(Subscription.self).map(Subscription.init))
return .setRooms(rooms)
}
func selectServer(store: SEStore, serverIndex: Int) {
store.dispatch(.selectServerIndex(serverIndex))
store.dispatch(fetchRooms)
}
func selectInitialServer(store: SEStore) -> SEAction? {
store.dispatch(fetchServers)
let serverCount = DatabaseManager.servers?.count ?? 0
let index = DatabaseManager.selectedIndex < serverCount ? DatabaseManager.selectedIndex : 0
selectServer(store: store, serverIndex: index)
return nil
}
|
mit
|
32df9b627590ca2f1f8b575bd6450ef4
| 31.377049 | 109 | 0.653671 | 4.238197 | false | false | false | false |
micolous/metrodroid
|
native/metrodroid/metrodroid/NFCReader.swift
|
1
|
15123
|
//
// NFCReader.swift
//
// Copyright 2019 Google
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
import Foundation
import CoreNFC
import UIKit
import metrolib
class NFCReader : NSObject, NFCTagReaderSessionDelegate, TagReaderFeedbackInterface {
private var session: NFCReaderSession?
private var navigationController: UINavigationController?
func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
print("NFC Session became active")
}
func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
print("NFC Session end \(error)")
}
class DesfireWrapper : ISO7816TransceiverSwiftWrapper {
var tag: NFCMiFareTag
init(tag: NFCMiFareTag) {
self.tag = tag
}
func getIdentifier() -> Data {
return tag.identifier
}
func transmit(input: Data,
callback__ callback: @escaping (ISO7816Transceiver.Capsule) -> Void) {
tag.sendMiFareISO7816Command(NFCISO7816APDU(data: input)!, completionHandler: {data,sw1,sw2,err in
callback(ISO7816Transceiver.Capsule(rep: data, sw1: sw1, sw2: sw2, err: err))})
}
}
class Iso7816Wrapper : ISO7816TransceiverSwiftWrapper {
var tag: NFCISO7816Tag
init(tag: NFCISO7816Tag) {
self.tag = tag
}
func getIdentifier() -> Data {
return tag.identifier
}
func transmit(input: Data, callback__ callback: @escaping (ISO7816Transceiver.Capsule) -> Void) {
tag.sendCommand(apdu: NFCISO7816APDU(data: input)!, completionHandler: {data,sw1,sw2,err in
callback(ISO7816Transceiver.Capsule(rep: data, sw1: sw1, sw2: sw2, err: err))})
}
}
class FelicaWrapper : FelicaTransceiverIOSSwiftWrapper {
func transmit(input: Data, callback: @escaping (FelicaTransceiverIOS.Capsule) -> Void) {
print("Sending \(input)")
tag.sendFeliCaCommand(commandPacket: input, completionHandler: {reply, err in callback(FelicaTransceiverIOS.Capsule(reply: reply, err: err))})
}
var tag: NFCFeliCaTag
init(tag: NFCFeliCaTag) {
self.tag = tag
}
func getIdentifier() -> Data {
return tag.currentIDm
}
}
class UltralightWrapper : UltralightTransceiverIOSSwiftWrapper {
func transmit(input: Data, callback_ callback: @escaping (UltralightTransceiverIOS.Capsule) -> Void) {
print("Sending \(input)")
tag.sendMiFareCommand(commandPacket: input, completionHandler: {reply, err in callback(UltralightTransceiverIOS.Capsule(reply: reply, err: err))})
}
var tag: NFCMiFareTag
init(tag: NFCMiFareTag) {
self.tag = tag
}
func getIdentifier() -> Data {
return tag.identifier
}
}
func postDump(card: Card) {
do {
let json = try CardSerializer.init().toJson(card: card)
print ("json=\(json)")
let url = try CardPersister.persistCard(card: card, json: json)
if Preferences.init().speakBalance {
if let balance = card.safeBalance?.formatCurrencyString(isBalance: true).unformatted {
let balanceStr = Utils.localizeString(RKt.R.string.balance_speech, balance)
Utils.speakText(voiceOutdata: balanceStr)
}
}
DispatchQueue.main.async {
let cr = CardViewController.create(json: json, url: url)
self.navigationController?.pushViewController(cr, animated: true)
}
} catch {
Utils.showError(viewController: self.navigationController!, msg: Utils.localizeString(RKt.R.string.ios_nfcreader_exception, "\(error)"))
}
}
func updateStatusText(msg: String) {
self.msg = msg
refresh()
}
func updateProgressBar(progress: Int32, max: Int32) {
self.cur = Int(progress)
self.max = Int(max)
refresh()
}
func showCardType(cardInfo: CardInfo?) {
}
private var msg: String
private var cur: Int
private var max: Int
override init() {
self.msg = Utils.localizeString(RKt.R.string.ios_nfcreader_tap)
self.cur = 0
self.max = 1
}
func refresh() {
session?.alertMessage = "\(msg) \(cur * 100 / max) %"
}
func statusConnecting(cardType: CardType) {
updateStatusText(msg: Utils.localizeString(RKt.R.string.ios_nfcreader_connecting, cardType.description()))
}
func statusReading(cardType: CardType) {
updateStatusText(msg: Utils.localizeString(RKt.R.string.ios_nfcreader_reading, cardType.description()))
}
class func connectionError(session: NFCTagReaderSession, err: Error?) {
session.invalidate(errorMessage:
Utils.localizeString(RKt.R.string.ios_nfcreader_connection_error, " \(String(describing: err))"))
}
func vicinityRead(tag: NFCISO15693Tag) -> Card {
let dg = DispatchGroup()
var sectors: [Data] = []
var partialRead: Bool = false
for sectorIdx in 0...255 {
dg.enter()
var reachedEnd: Bool = false
tag.readSingleBlock(requestFlags: RequestFlag(rawValue: 0x22), blockNumber: UInt8(sectorIdx), completionHandler: {
data, errorIn in
print ("Read \(sectorIdx) -> \(data), \(String(describing: errorIn))")
if (errorIn != nil && (errorIn! as NSError).code == 102) {
reachedEnd = true
} else if (errorIn != nil && (errorIn! as NSError).code == 100) {
partialRead = true
} else {
sectors.append(data)
}
dg.leave()
})
dg.wait()
if (reachedEnd || partialRead) {
break
}
}
let nfcv = NFCVCard(sysInfo: nil,
pages: sectors.map { NFCVPage(dataRaw: UtilsKt.toImmutable($0 as Data),
isUnauthorized: $0.isEmpty) }, isPartialRead: partialRead)
return Card(tagId: UtilsKt.toImmutable(tag.identifier).reverseBuffer(), scannedAt: TimestampFull.Companion.init().now(),
label: nil, mifareClassic: nil, mifareDesfire: nil, mifareUltralight: nil, cepasCompat: nil, felica: nil, iso7816: nil, vicinity: nfcv)
}
func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
if (tags.count < 1) {
print ("No tags found")
return
}
let tag = tags.first!
print ("Found tag \(tag)")
switch(tag) {
case .miFare(let mifare):
switch (mifare.mifareFamily) {
case NFCMiFareFamily.desfire:
statusConnecting(cardType: .mifaredesfire)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
self.statusReading(cardType: .mifaredesfire)
DispatchQueue.global().async {
print("swift async")
do {
let card = try DesfireCardReaderIOS.init().dump(wrapper: DesfireWrapper(tag: mifare), feedback: self)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
} catch {
session.invalidate(errorMessage: error.localizedDescription)
}
}
})
break
case NFCMiFareFamily.ultralight:
statusConnecting(cardType: .mifareultralight)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
self.statusReading(cardType: .mifareultralight)
DispatchQueue.global().async {
print("swift async")
do {
let card = try UltralightCardReaderIOS.init().dump(wrapper: UltralightWrapper(tag: mifare), feedback: self)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
} catch {
session.invalidate(errorMessage: error.localizedDescription)
}
}
})
break
case .plus:
statusConnecting(cardType: .mifareplus)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
self.statusReading(cardType: .mifaredesfire)
DispatchQueue.global().async {
print("swift async")
do {
let card = try PlusCardReaderIOS.init().dump(wrapper: UltralightWrapper(tag: mifare), feedback: self)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
} catch {
session.invalidate(errorMessage: error.localizedDescription)
}
}
})
break
default:
session.invalidate(errorMessage: Utils.localizeString(RKt.R.string.ios_unknown_mifare, "\(mifare)"))
break
}
break
case .iso7816(let iso):
statusConnecting(cardType: .iso7816)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
self.statusReading(cardType: .iso7816)
DispatchQueue.global().async {
print("swift async")
do {
let card = try ISO7816CardReaderIOS.init().dump(wrapper: Iso7816Wrapper(tag: iso), feedback: self)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
} catch {
session.invalidate(errorMessage: error.localizedDescription)
}
}
})
case .feliCa(let felica):
statusConnecting(cardType: .felica)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
print("idm:\(felica.currentIDm.base64EncodedString()) syscode:\(felica.currentSystemCode.base64EncodedString())")
self.statusReading(cardType: .felica)
DispatchQueue.global().async {
print("swift async")
do {
let card = try FelicaCardReaderIOS.init().dump(wrapper: FelicaWrapper(tag: felica), defaultSysCode: felica.currentSystemCode, feedback: self)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
} catch {
session.invalidate(errorMessage: error.localizedDescription)
}
}
})
case .iso15693(let vicinity):
statusConnecting(cardType: .vicinity)
session.connect(to: tag, completionHandler: {
err in
if (err != nil) {
NFCReader.connectionError(session: session, err: err)
return
}
self.statusReading(cardType: .vicinity)
DispatchQueue.global().async {
print("swift async")
let card = self.vicinityRead(tag: vicinity)
if (!card.isPartialRead) {
self.updateProgressBar(progress: 1, max: 1)
}
session.invalidate()
self.postDump(card: card)
}
})
default:
session.invalidate(errorMessage:
Utils.localizeString(RKt.R.string.ios_unknown_tag, "\(tag)"))
}
}
func start(navigationController: UINavigationController?) {
print ("Reading available: \(NFCTagReaderSession.readingAvailable)")
session = NFCTagReaderSession(pollingOption: [
.iso14443, .iso18092, .iso15693],
delegate: self)
session!.alertMessage = Utils.localizeString(RKt.R.string.ios_nfcreader_tap)
session!.begin()
self.navigationController = navigationController
}
}
|
gpl-3.0
|
8a2e2d25bd5181f2f56b00024a44859d
| 39.114058 | 165 | 0.518879 | 4.856455 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/API/Requests/Notifications/SaveNotificationRequest.swift
|
1
|
2034
|
//
// SaveNotificationRequest.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 16.04.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
final class SaveNotificationRequest: APIRequest {
typealias APIResourceType = SaveNotificationResource
let requiredVersion = Version(0, 63, 0)
let method: HTTPMethod = .post
let path = "/api/v1/rooms.saveNotification"
let rid: String
let notificationPreferences: NotificationPreferences
init(rid: String, notificationPreferences: NotificationPreferences) {
self.rid = rid
self.notificationPreferences = notificationPreferences
}
func body() -> Data? {
var body = JSON([
"roomId": rid,
"notifications": [:]
])
body["notifications"]["disableNotifications"].string = notificationPreferences.disableNotifications ? "1" : "0"
body["notifications"]["emailNotifications"].string = notificationPreferences.emailNotifications.rawValue
body["notifications"]["audioNotifications"].string = notificationPreferences.audioNotifications.rawValue
body["notifications"]["mobilePushNotifications"].string = notificationPreferences.mobilePushNotifications.rawValue
body["notifications"]["audioNotificationValue"].string = notificationPreferences.audioNotificationValue.rawValue
body["notifications"]["desktopNotificationDuration"].string = String(notificationPreferences.desktopNotificationDuration)
body["notifications"]["hideUnreadStatus"].string = notificationPreferences.hideUnreadStatus ? "1" : "0"
let string = body.rawString()
let data = string?.data(using: .utf8)
return data
}
var contentType: String? {
return "application/json"
}
}
final class SaveNotificationResource: APIResource {
var success: Bool {
return raw?["success"].boolValue ?? false
}
var errorMessage: String? {
return raw?["error"].string
}
}
|
mit
|
1acca46bf5568cfe282232535d083e50
| 32.883333 | 129 | 0.699459 | 4.995086 | false | false | false | false |
NathanE73/Blackboard
|
Tests/BlackboardFrameworkTests/Symbol Assets/BlackboardSymbolTests.swift
|
1
|
6607
|
//
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import BlackboardFramework
class BlackboardSymbolTests: XCTestCase {
let iOSAvailability = Availability.available(platform: .iOS, version: Version(13, 0))
func testNumber14SquareFill() {
let blackboardSymbol = BlackboardSymbol(name: "14.square.fill", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "14.square.fill")
XCTAssertEqual(blackboardSymbol.functionName, "symbolNumber14SquareFill")
XCTAssertEqual(blackboardSymbol.caseName, "number14SquareFill")
}
func testCaseSymbol() {
let blackboardSymbol = BlackboardSymbol(name: "case", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "case")
XCTAssertEqual(blackboardSymbol.functionName, "symbolCase")
XCTAssertEqual(blackboardSymbol.caseName, "case")
}
func testCaseSymbolFill() {
let blackboardSymbol = BlackboardSymbol(name: "case.fill", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "case.fill")
XCTAssertEqual(blackboardSymbol.functionName, "symbolCaseFill")
XCTAssertEqual(blackboardSymbol.caseName, "caseFill")
}
func testChevronDown() {
let blackboardSymbol = BlackboardSymbol(name: "chevron.down", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "chevron.down")
XCTAssertEqual(blackboardSymbol.functionName, "symbolChevronDown")
XCTAssertEqual(blackboardSymbol.caseName, "chevronDown")
}
func testChevronUp() {
let blackboardSymbol = BlackboardSymbol(name: "chevron.up", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "chevron.up")
XCTAssertEqual(blackboardSymbol.functionName, "symbolChevronUp")
XCTAssertEqual(blackboardSymbol.caseName, "chevronUp")
}
func testDieFace1() {
let blackboardSymbol = BlackboardSymbol(name: "die.face.1", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "die.face.1")
XCTAssertEqual(blackboardSymbol.functionName, "symbolDieFace1")
XCTAssertEqual(blackboardSymbol.caseName, "dieFace1")
}
func testDieFace4() {
let blackboardSymbol = BlackboardSymbol(name: "die.face.4", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "die.face.4")
XCTAssertEqual(blackboardSymbol.functionName, "symbolDieFace4")
XCTAssertEqual(blackboardSymbol.caseName, "dieFace4")
}
func testInfinityCircleFill() {
let blackboardSymbol = BlackboardSymbol(name: "infinity.circle.fill", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "infinity.circle.fill")
XCTAssertEqual(blackboardSymbol.functionName, "symbolInfinityCircleFill")
XCTAssertEqual(blackboardSymbol.caseName, "infinityCircleFill")
}
func testMinusCircleFill() {
let blackboardSymbol = BlackboardSymbol(name: "minus.circle.fill", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "minus.circle.fill")
XCTAssertEqual(blackboardSymbol.functionName, "symbolMinusCircleFill")
XCTAssertEqual(blackboardSymbol.caseName, "minusCircleFill")
}
func testPerson() {
let blackboardSymbol = BlackboardSymbol(name: "person", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "person")
XCTAssertEqual(blackboardSymbol.functionName, "symbolPerson")
XCTAssertEqual(blackboardSymbol.caseName, "person")
}
func testPerson2() {
let blackboardSymbol = BlackboardSymbol(name: "person2", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "person2")
XCTAssertEqual(blackboardSymbol.functionName, "symbolPerson2")
XCTAssertEqual(blackboardSymbol.caseName, "person2")
}
func testPlusCircleFill() {
let blackboardSymbol = BlackboardSymbol(name: "plus.circle.fill", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "plus.circle.fill")
XCTAssertEqual(blackboardSymbol.functionName, "symbolPlusCircleFill")
XCTAssertEqual(blackboardSymbol.caseName, "plusCircleFill")
}
func testReturnSymbol() {
let blackboardSymbol = BlackboardSymbol(name: "return", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "return")
XCTAssertEqual(blackboardSymbol.functionName, "symbolReturn")
XCTAssertEqual(blackboardSymbol.caseName, "return")
}
func testRepeatSymbol() {
let blackboardSymbol = BlackboardSymbol(name: "repeat", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "repeat")
XCTAssertEqual(blackboardSymbol.functionName, "symbolRepeat")
XCTAssertEqual(blackboardSymbol.caseName, "repeat")
}
func testRepeatSymbolCircle() {
let blackboardSymbol = BlackboardSymbol(name: "repeat.circle", iOSAvailability: iOSAvailability)
XCTAssertEqual(blackboardSymbol.name, "repeat.circle")
XCTAssertEqual(blackboardSymbol.functionName, "symbolRepeatCircle")
XCTAssertEqual(blackboardSymbol.caseName, "repeatCircle")
}
}
|
mit
|
1c66735dd6d9aba9f32594e53fe7f55a
| 42.183007 | 111 | 0.716664 | 4.699147 | false | true | false | false |
google/JacquardSDKiOS
|
Tests/ComponentInfoCommandTests.swift
|
1
|
4627
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import JacquardSDK
class ComponentInfoCommandTests: XCTestCase {
struct CatchLogger: Logger {
func log(level: LogLevel, file: String, line: Int, function: String, message: () -> String) {
let _ = message()
if level == .assertion {
expectation.fulfill()
}
}
var expectation: XCTestExpectation
}
override func setUp() {
super.setUp()
let logger = PrintLogger(
logLevels: [.debug, .info, .warning, .error, .assertion],
includeSourceDetails: true
)
setGlobalJacquardSDKLogger(logger)
}
override func tearDown() {
// Other tests may run in the same process. Ensure that any fake logger fulfillment doesn't
// cause any assertions later.
JacquardSDK.setGlobalJacquardSDKLogger(JacquardSDK.createDefaultLogger())
super.tearDown()
}
func testRequestCreation() {
let expectedComponentID: UInt32 = 0
let expectedDomain: Google_Jacquard_Protocol_Domain = .base
let expectedOpcode: Google_Jacquard_Protocol_Opcode = .deviceinfo
// Compose the request.
let componentInfoCommandRequest = ComponentInfoCommand(componentID: expectedComponentID)
guard let request = componentInfoCommandRequest.request as? Google_Jacquard_Protocol_Request
else {
XCTFail("Unexpected type for the request.")
return
}
// Validate the request.
XCTAssertEqual(request.domain, expectedDomain, "Device info request has wrong domain.")
XCTAssertEqual(request.opcode, expectedOpcode, "Device info request has wrong opcode.")
XCTAssertEqual(
request.componentID, expectedComponentID, "Device info request has wrong componentID.")
XCTAssert(request.hasGoogle_Jacquard_Protocol_DeviceInfoRequest_deviceInfo)
let infoRequest = request.Google_Jacquard_Protocol_DeviceInfoRequest_deviceInfo
XCTAssertEqual(
infoRequest.component, expectedComponentID, "Wrong component set for device info request.")
}
func testGoodResponse() {
let goodResponseExpectation = expectation(description: "goodResponseExpectation")
let componentInfoCommandRequest = ComponentInfoCommand(componentID: 0)
let goodProto = Google_Jacquard_Protocol_Response.with {
let deviceInfo = Google_Jacquard_Protocol_DeviceInfoResponse.with {
$0.firmwareMajor = 1
$0.firmwareMinor = 96
$0.firmwarePoint = 0
}
$0.Google_Jacquard_Protocol_DeviceInfoResponse_deviceInfo = deviceInfo
}
componentInfoCommandRequest.parseResponse(outerProto: goodProto).assertSuccess { _ in
goodResponseExpectation.fulfill()
}
wait(for: [goodResponseExpectation], timeout: 0.5)
}
func testMalformedResponse() {
let malformedResponseExpectation = expectation(description: "malformedResponseExpectation")
let componentInfoCommandRequest = ComponentInfoCommand(componentID: 0)
let malformedResponse = Google_Jacquard_Protocol_Response.with {
// Providing wrong response(config write command response).
let config = Google_Jacquard_Protocol_BleConfiguration()
let ujtConfigResponse = Google_Jacquard_Protocol_UJTConfigResponse.with {
$0.bleConfig = config
}
$0.Google_Jacquard_Protocol_UJTConfigResponse_configResponse = ujtConfigResponse
}
componentInfoCommandRequest.parseResponse(outerProto: malformedResponse).assertFailure { _ in
malformedResponseExpectation.fulfill()
}
wait(for: [malformedResponseExpectation], timeout: 0.5)
}
/// Proto payload is Any type, so we need to ensure a bad payload is safely ignored.
func testBadResponse() {
let badResponseExpectation = expectation(description: "badResponseExpectation")
jqLogger = CatchLogger(expectation: badResponseExpectation)
let componentInfoCommandRequest = ComponentInfoCommand(componentID: 0)
let badResponse = Google_Jacquard_Protocol_Color()
componentInfoCommandRequest.parseResponse(outerProto: badResponse).assertFailure()
wait(for: [badResponseExpectation], timeout: 0.5)
}
}
|
apache-2.0
|
ff3c29a3951f41182b9cc42eac2a1852
| 36.314516 | 97 | 0.73914 | 4.631632 | false | true | false | false |
Skrapit/ALCameraViewController
|
ALCameraViewController/ViewController/ConfirmViewController.swift
|
1
|
4265
|
//
// ConfirmViewController.swift
// ALCameraViewController
//
// Created by Zhu Wu on 8/25/17.
// Copyright © 2017 zero. All rights reserved.
//
import Foundation
import Photos
public class ConfirmViewController: UIViewController {
let image: UIImage?
let asset: PHAsset?
@IBOutlet weak var imageView: UIImageView!
// @IBOutlet weak var backButton: UIButton!
// @IBOutlet weak var doneButton: UIButton!
lazy var nextBarButtonItem: UIBarButtonItem = {
var item = UIBarButtonItem(title: localizedString("confirm.done"), style: .plain, target: nil, action: nil)
item.tintColor = #colorLiteral(red: 0.2392156863, green: 0.8274509804, blue: 0.3960784314, alpha: 1)
return item
}()
lazy var backBarButtonItem: UIBarButtonItem = {
let buttonImage = UIImage(named: "nav_back", in: CameraGlobals.shared.bundle, compatibleWith: nil)
var item = UIBarButtonItem(image: buttonImage, style: .plain, target: nil, action: nil)
return item
}()
public var onComplete: CameraViewCompletion?
public override var prefersStatusBarHidden: Bool {
return true
}
public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return UIStatusBarAnimation.slide
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
public init(_ image: UIImage?, _ asset: PHAsset?) {
self.image = image
self.asset = asset
super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle)
}
public required init?(coder aDecoder: NSCoder) {
image = nil
asset = nil
super.init(coder: aDecoder)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.title = localizedString("confirm.viewtitle")
self.navigationItem.leftBarButtonItem = backBarButtonItem
if let image = image {
configureWithImage(image)
self.navigationItem.rightBarButtonItem = nextBarButtonItem
}
}
private func configureWithImage(_ image: UIImage) {
setupButtonActions()
imageView.image = image
}
func setupButtonActions() {
backBarButtonItem.itemAction = { [weak self] in self?.navigationController?.popViewController(animated: true) }
nextBarButtonItem.itemAction = { [weak self] in self?.confirmPhoto() }
}
func confirmPhoto() {
guard let image = imageView.image else {
return
}
disable()
// imageView.isHidden = true
let spinner = showSpinner()
// if let asset = asset {
// var fetcher = SingleImageFetcher()
// .onSuccess { [weak self] image in
// self?.onComplete?(image, self?.asset)
// self?.hideSpinner(spinner)
// self?.enable()
// }
// .onFailure { [weak self] error in
// self?.hideSpinner(spinner)
// self?.showNoImageScreen(error)
// }
// .setAsset(asset)
// if allowsCropping {
// let rect = normalizedRect(makeProportionalCropRect(), orientation: image.imageOrientation)
// fetcher = fetcher.setCropRect(rect)
// }
//
// fetcher = fetcher.fetch()
// } else {
let newImage = image
onComplete?(newImage, asset)
hideSpinner(spinner)
enable()
// }
}
internal func cancel() {
onComplete?(nil, nil)
}
func showSpinner() -> UIActivityIndicatorView {
let spinner = UIActivityIndicatorView()
spinner.activityIndicatorViewStyle = .white
spinner.center = view.center
spinner.startAnimating()
view.addSubview(spinner)
view.bringSubview(toFront: spinner)
return spinner
}
func hideSpinner(_ spinner: UIActivityIndicatorView) {
spinner.stopAnimating()
spinner.removeFromSuperview()
}
func disable() {
nextBarButtonItem.isEnabled = false
}
func enable() {
nextBarButtonItem.isEnabled = true
}
func showNoImageScreen(_ error: NSError) {
let permissionsView = PermissionsView(frame: view.bounds)
let desc = localizedString("error.cant-fetch-photo.description")
permissionsView.configureInView(view, title: error.localizedDescription, description: desc, completion: { [weak self] in self?.cancel() })
}
}
|
mit
|
7499b3b5721465ef34e02aed8b153638
| 25.81761 | 142 | 0.668621 | 4.575107 | false | false | false | false |
acecilia/DTUSensors
|
DTUSensors/PeripheralViewController.swift
|
1
|
12174
|
//
// MasterViewController.swift
// DTUSensors3
//
// Created by Andres on 18/3/15.
// Copyright (c) 2015 Andres. All rights reserved.
//
import UIKit
import CoreBluetooth
/**
* Controller for the peripheral view
*/
class PeripheralViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CBPeripheralDelegate {
/// Previous controller (centralManager). Used to go back when the watchdog finishes
var previousVC : CentralManagerViewController!
/// Object that stores all the information related with the sensors, baudrate...
var TPC = TransmissionParametersController()
/// Texfield to set the baudrate value
@IBOutlet weak var textFieldBaudrate: UITextField!
/// Slider to set the baudrate value
@IBOutlet weak var sliderBaudrate: UISlider!
/// Table with the sensors
@IBOutlet weak var tableView: UITableView!
/// Object that stores the information of the BLE device selected
var selectedDevice : CustomPeripheralObject!
/// Identifier of the services of the BLE device (specific for adafruit BLE device nRF8001)
let BLEServiceUUID = CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
/// Identifier of the tx characteristic of the BLE device (specific for adafruit BLE device nRF8001)
let BLEtxUUID = CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
/// Identifier of the rx characteristic of the BLE device (specific for adafruit BLE device nRF8001)
let BLErxUUID = CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E")
/// Whatchdog that limits the time used for get the services of the BLE device (tell you to choose other device if the chosen one is not the expected one)
var whatchdog : NSTimer!
// MARK: - Functions related with the viewController
/**
Reloads table and configurates the cell selected
:param: animated
*/
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
if let indexPathForSelectedRow = tableView.indexPathForSelectedRow()
{
tableView.deselectRowAtIndexPath(indexPathForSelectedRow, animated: true)
}
}
/**
Invalidate watchdog to avoid getting the alert out of the viewController
:param: animated
*/
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
whatchdog.invalidate()
}
/**
Loads TransmissionParametersController from NSUserDefaults, enables watchdog
*/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
TPC.retrieveTPC()
textFieldBaudrate.text = "\(TPC.baudrate)"
sliderBaudrate.value = Float(TPC.baudrate)
if let startButton = self.navigationItem.rightBarButtonItem
{
startButton.enabled = false
}
whatchdog = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "communicationError", userInfo: nil, repeats: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Whatchdog related
/**
Gets called when the watchdog reaches the end, raising an alert to the user and returning to the previous controller
*/
func communicationError()
{
let alertController = UIAlertController(title: "Error in the communication", message:
"Something happened while initiating the communication with the arduino. If you can not fix this issue try to reset the arduino and restart the iPhone", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
self.navigationController?.popViewControllerAnimated(true)
previousVC.presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - Segues
/**
Manages the movements to other controllers
:param: segue The corresponding segue
:param: sender The sender
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetailAC" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
if let controller = segue.destinationViewController as? ACDetailViewController
{
controller.sensor = TPC.sensors[indexPath.row]
}
}
}else if segue.identifier == "showDetailGPS" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
if let controller = segue.destinationViewController as? GPSDetailViewController
{
controller.sensor = TPC.sensors[indexPath.row]
}
}
}else if segue.identifier == "showDetailGCP" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
if let controller = segue.destinationViewController as? GCPDetailViewController
{
controller.sensor = TPC.sensors[indexPath.row]
}
}
}else if segue.identifier == "startTransmision" {
TPC.baudrate = Int(round(sliderBaudrate.value))
TPC.safeTPC()
//Prepare next view
if let controller = segue.destinationViewController as? TransmisionViewController
{
controller.selectedDevice = selectedDevice
controller.previousVC = self
controller.TPC = TPC
}
println("The baudrate for the communications is: \(TPC.baudrate)\n")
}
}
// MARK: - TableView delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TPC.sensors.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if let label = cell.contentView.viewWithTag(51) as? UILabel
{
label.text = TPC.sensors[indexPath.row].name
}
if let switchObject = cell.contentView.viewWithTag(52) as? UISwitch
{
switchObject.on = TPC.sensors[indexPath.row].state
}
if let segmentedControl = cell.contentView.viewWithTag(53) as? UISegmentedControl
{
segmentedControl.setTitle("Parameters=\(TPC.sensors[indexPath.row].numberOfParameters)", forSegmentAtIndex: 0)
segmentedControl.setTitle("Size=\(TPC.sensors[indexPath.row].lengthOfParameter) bytes", forSegmentAtIndex: 1)
}
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showDetail\(TPC.sensors[indexPath.row].name)", sender: self)
}
// MARK: - BLE related
/**
Looks for the service inside adafruit BLE device
:param: peripheral The peripheral
:param: error Error description
*/
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
for service in peripheral.services {
if let thisService = service as? CBService
{
// List of UUIDs related with services
println("--peripheral didDiscoverServices--\nService:")
println(thisService)
if service.UUID == BLEServiceUUID {
// Discover characteristics of service
peripheral.discoverCharacteristics(nil, forService: thisService)
}
}
}
}
/**
Discovers the characteristics of the service and looks for rx and tx characteristics presented in adafruit BLE device. if they are correct it invalidates the watchdog, allowing the user start the transmission
:param: peripheral The peripheral
:param: service Service description
:param: error Error description
*/
func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) {
println("--peripheral didDiscoverCharacteristicsForService--\nService:")
println(service)
println("Characteristics:")
// check the uuid of each characteristic to find tx and rx
for charateristic in service.characteristics {
let thisCharacteristic = charateristic as! CBCharacteristic
println(thisCharacteristic)
// check for tx characteristic
if thisCharacteristic.UUID == BLEtxUUID {
selectedDevice.BLEtxCharacteristic = thisCharacteristic
}
// check for rx characteristic
if thisCharacteristic.UUID == BLErxUUID {
selectedDevice.BLErxCharacteristic = thisCharacteristic
selectedDevice.peripheral.setNotifyValue(true, forCharacteristic: thisCharacteristic)
}
}
if selectedDevice.BLEtxCharacteristic != nil && selectedDevice.BLErxCharacteristic != nil
{
//We enable the button to transmit after the characteristics have been found
if let startButton = self.navigationItem.rightBarButtonItem
{
startButton.enabled = true
}
whatchdog.invalidate()
}
}
// MARK: - IBActions
/**
Manages changes in the switches that controls which sensors are enabled for transmission
:param: sender The switch
*/
@IBAction func swithValueChanged(sender: UISwitch)
{
if let cell = sender.superview?.superview as? UITableViewCell
{
let indexPath = self.tableView.indexPathForCell(cell)
if let row = indexPath?.row
{
TPC.sensors[row].state = sender.on
}
}
}
/**
Manages changes in the value of the slider that controls the baudrate value
:param: sender The slider
*/
@IBAction func sliderBaudrateValueChanged(sender: AnyObject) {
textFieldBaudrate.text = "\(Int(round(sliderBaudrate.value)))"
sliderBaudrate.value = round(sliderBaudrate.value)
}
/**
Gets called when user finish editing the text field corresponding to tha baudrate
:param: sender The textField
*/
@IBAction func textFieldBaudrateEditingDidEnd(sender: AnyObject) {
textFieldBaudrateEnd()
}
/**
Synchronize the values shown in the textfield and in the slider
*/
func textFieldBaudrateEnd ()
{
let futureValue = NSNumberFormatter().numberFromString(textFieldBaudrate.text)
if futureValue != nil && sliderBaudrate.minimumValue <= futureValue!.floatValue && futureValue!.floatValue <= sliderBaudrate.maximumValue
{
sliderBaudrate.value = futureValue!.floatValue
}
else
{
textFieldBaudrate.text = "\(Int(round(sliderBaudrate.value)))"
}
}
/**
Asks the delegate if the text field should process the pressing of the return button
:param: textField The textField
:returns: The answer
*/
func textFieldShouldReturn(textField: UITextField) -> Bool
{
textField.resignFirstResponder()
if(textField == textFieldBaudrate)
{
textFieldBaudrateEnd()
}
return false
}
}
|
mit
|
2de8311aa972c390584ee85b9db4a550
| 35.668675 | 212 | 0.641695 | 5.306888 | false | false | false | false |
lizhuoli1126/e-lexer
|
other/e-lexer-swift/e-lexer/main.swift
|
1
|
3938
|
//
// main.swift
// e-lexer
//
// Created by lizhuoli on 15/12/5.
// Copyright © 2015年 lizhuoli. All rights reserved.
//
import Foundation
func main(){
let argv = Process.arguments
var path = ""
if argv.count < 2 {
path = "./input.l"
} else {
path = argv[1]
}
var state = 0
let scanner = Scanner(path: path)
var currentProduction = Production()
var productionList:[Production] = []
while(true){
guard let input = scanner.getNextChar() else {
if let _ = scanner.getNextLine() {
continue
} else { //End state
print("Grammar is legal")
break
}
}
print("Current \(input)")
switch (state) {
case 0: //Start state
if (input >= "A" && input <= "Z") {
state = 1
currentProduction.left = Symbol(value: input, type: .NonTerminal)
continue
} else {
Error.lexError(scanner.getLineNum())
}
case 1:
if (input == "-") {
state = 2
continue
} else {
Error.lexError(scanner.getLineNum())
}
case 2:
if (input == ">") {
state = 3
continue
} else {
Error.lexError(scanner.getLineNum())
}
case 3:
if ((input >= "a" && input <= "z") || (input == "(") || (input == ")")
|| (input == "+") || (input == "-")
|| (input == "*") || (input == "/")) { //a-zA-Z()+-*/
state = 4
currentProduction.right.append(Symbol(value: input, type: .Terminal))
continue
} else if (input >= "A" && input <= "Z") {
state = 4
currentProduction.right.append(Symbol(value: input, type: .NonTerminal))
continue
} else if (input == "\\") {
state = 5
//TODO
continue
} else {
Error.lexError(scanner.getLineNum())
}
case 4:
if ((input >= "a" && input <= "z") || (input >= "A" && input <= "Z")
|| (input == "(") || (input == ")") || (input == "+") || (input == "-")
|| (input == "*") || (input == "/")) { //a-zA-Z()+-*/
state = 4
currentProduction.right.append(Symbol(value: input, type: .Terminal))
continue
} else if (input == "\\") {
state = 5
//TODO
continue
} else if (input == "|") {
state = 4
let newProduction = Production()
productionList.append(currentProduction)
newProduction.left = currentProduction.left
currentProduction = newProduction
continue
} else if (input == "\n") {
state = 0
productionList.append(currentProduction)
currentProduction = Production()
print(productionList[0].left)
continue
} else {
Error.lexError(scanner.getLineNum())
}
case 5:
if (input == "e") {
state = 4
currentProduction.right.append(Symbol(value: "ε", type: .Terminal))
continue
} else {
Error.lexError(scanner.getLineNum())
}
default: //Error state for -2
print("Grammar is illegal!")
exit(0)
}
}
for p in productionList {
print("Production: left: \(p.left), right: \(p.right)")
}
}
main()
|
mit
|
03989f01cbf6c279a266818f612a8213
| 29.742188 | 89 | 0.409253 | 4.739759 | false | false | false | false |
devpunk/velvet_room
|
Source/View/SaveData/VSaveDataListCellTitle.swift
|
1
|
1535
|
import UIKit
final class VSaveDataListCellTitle:VSaveDataListCell
{
private weak var label:UILabel!
private let kMarginHorizontal:CGFloat = 10
private let kFontSize:CGFloat = 17
override init(frame:CGRect)
{
super.init(frame:frame)
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.isUserInteractionEnabled = false
label.numberOfLines = 0
label.font = UIFont.medium(
size:kFontSize)
label.textColor = UIColor.colourBackgroundDark
self.label = label
addSubview(label)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:kMarginHorizontal)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:label)
}
required init?(coder:NSCoder)
{
return nil
}
override func config(
controller:CSaveData,
model:MSaveDataProtocol)
{
super.config(
controller:controller,
model:model)
guard
let itemTitle:MSaveDataTitle = model as? MSaveDataTitle
else
{
return
}
label.text = itemTitle.title
}
}
|
mit
|
7217960ce9e6a33a65c7ffba3dd1cf07
| 23.365079 | 67 | 0.575244 | 5.581818 | false | false | false | false |
JiongXing/PhotoBrowser
|
Example/Example/MoreDetailViewController.swift
|
1
|
695
|
//
// MoreDetailViewController.swift
// Example
//
// Created by JiongXing on 2019/11/26.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
class MoreDetailViewController: UIViewController {
lazy var label: UILabel = {
let lab = UILabel()
lab.textColor = .black
lab.text = "< 更多详情 >"
lab.textAlignment = .center
return lab
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(label)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
label.frame = view.bounds
}
}
|
mit
|
a807826891e3bea775565b16f10f7c9f
| 20.4375 | 52 | 0.602041 | 4.666667 | false | false | false | false |
bignerdranch/DeferredTCPSocket
|
DeferredTCPSocket/DeferredTCPSocket/DeferredWriter.swift
|
1
|
1905
|
//
// DeferredWriter.swift
// DeferredIO
//
// Created by John Gallagher on 9/12/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
#if os(iOS)
import Deferred
#else
import DeferredMac
#endif
public final class DeferredWriter {
private let queue = dispatch_queue_create("DeferredWriter", DISPATCH_QUEUE_SERIAL)
private let source: dispatch_source_t
private let timerSource: dispatch_source_t
private let operationQueue = NSOperationQueue()
private var closed = false
public init(fd: Int32, cancelHandler: () -> ()) {
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, UInt(fd), 0, queue)
dispatch_source_set_cancel_handler(source, cancelHandler)
timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
operationQueue.maxConcurrentOperationCount = 1
}
deinit {
// NSLog("DEINIT: \(self)")
close()
}
public func close() {
if !closed {
operationQueue.cancelAllOperations()
operationQueue.waitUntilAllOperationsAreFinished()
dispatch_source_cancel(source)
dispatch_resume(source)
dispatch_source_cancel(timerSource)
dispatch_resume(timerSource)
closed = true
}
}
public func writeData(data: NSData, withTimeout timeout: NSTimeInterval? = nil) -> Deferred<WriteResult> {
let op = DeferredWriteOperation(data: data, queue: queue, source: source, timerSource: timerSource, timeout: timeout)
operationQueue.addOperation(op)
return op.deferred
}
public func writeString(string: String, withEncoding encoding: NSStringEncoding = NSUTF8StringEncoding, timeout: NSTimeInterval? = nil) -> Deferred<WriteResult> {
return writeData(string.dataUsingEncoding(encoding, allowLossyConversion: false)!)
}
}
|
mit
|
8607c28b781e1a2c1d8a00c1799b1b5d
| 30.245902 | 166 | 0.680315 | 4.546539 | false | false | false | false |
scarlettwu93/test
|
Example/Tests/Tests.swift
|
1
|
1171
|
// https://github.com/Quick/Quick
import Quick
import Nimble
import test
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
|
mit
|
2571672c2135b0dc79e68837e032ed38
| 22.3 | 63 | 0.360515 | 5.469484 | false | false | false | false |
brunophilipe/Noto
|
Noto/View Controllers/Info Bar/HUDInfoBarController.swift
|
1
|
2315
|
//
// HUDInfoBarController.swift
// Noto
//
// Created by Bruno Philipe on 5/3/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
class HUDInfoBarController: NSViewController, InfoBar
{
@IBOutlet private var labelCharacters: NSTextField!
@IBOutlet private var labelWords: NSTextField!
@IBOutlet private var labelLines: NSTextField!
@IBOutlet private var labelEncoding: NSTextField!
var animatedViews: [NSView]
{
return [labelCharacters, labelWords, labelLines]
}
override func viewDidLoad()
{
super.viewDidLoad()
self.view.layer?.cornerRadius = 10
labelCharacters.menu = makeCopyContextMenuForView(labelCharacters)
labelWords.menu = makeCopyContextMenuForView(labelWords)
labelLines.menu = makeCopyContextMenuForView(labelLines)
}
func setDarkMode(_ isDark: Bool)
{
let textColor = isDark ? NSColor.white : NSColor.black
labelCharacters.textColor = textColor
labelWords.textColor = textColor
labelLines.textColor = textColor
labelEncoding.textColor = textColor
let backgroundColor = isDark ? NSColor.darkGray : NSColor.white
self.view.layer?.backgroundColor = backgroundColor.withAlphaComponent(0.45).cgColor
}
func setLinesCount(_ string: String)
{
labelLines.stringValue = string
}
func setWordsCount(_ string: String)
{
labelWords.stringValue = string
}
func setCharactersCount(_ string: String)
{
labelCharacters.stringValue = string
}
func setEncoding(_ string: String)
{
labelEncoding.stringValue = string
}
static func make() -> HUDInfoBarController
{
return HUDInfoBarController(nibName: "HUDInfoBarController", bundle: Bundle.main)
}
}
|
gpl-3.0
|
988e5305cdcaad8bc75c7cc37692e292
| 26.223529 | 85 | 0.753241 | 3.837479 | false | false | false | false |
apple/swift-experimental-string-processing
|
Tests/Prototypes/TourOfTypes/Literal.swift
|
1
|
4714
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: - Pitched Compiler/library interface
/// Conform to this to support regex literals
protocol ExpressibleByRegexLiteral {
associatedtype Builder: RegexLiteralBuilderProtocol
init(builder: Builder)
}
/// Builder conforms to this for compiler-library API
protocol RegexLiteralBuilderProtocol {
/// Opaquely identify something built
associatedtype ASTNodeId = UInt
/// NOTE: This will likely not be a requirement but could be ad-hoc name lookup
mutating func buildCharacterClass_d() -> ASTNodeId
/// Any post-processing or partial compilation
///
/// NOTE: we might want to make this `throws`, capable of communicating
/// compilation failure if conformer is constant evaluable.
mutating func finalize()
}
/*
TODO: We will probably want defaulting mechanisms, such as:
* Ability for a conformer to take a meta-character as
just an escaped character
* Ability for a conformer to use function decls for feature
set communication alone, and have default impl build just
echo the string for an engine
*/
// MARK: - Semantic levels
/// Dynamic notion of a specified semantics level for a regex
enum SemanticsLevel {
case graphemeCluster
case scalar
case posix // different than ASCII?
// ... code units ...
}
/// Conformers can be ran as a regex / pattern
protocol RegexComponent {
var level: SemanticsLevel? { get }
}
/// Provide the option to encode semantic level statically
protocol RegexLiteralProtocol: ExpressibleByRegexLiteral {
associatedtype ScalarSemanticRegex: RegexComponent
associatedtype GraphemeSemanticRegex: RegexComponent
associatedtype POSIXSemanticRegex: RegexComponent
associatedtype UnspecifiedSemanticRegex: RegexComponent = RegexLiteral
var scalarSemantic: ScalarSemanticRegex { get }
var graphemeSemantic: GraphemeSemanticRegex { get }
var posixSemantic: POSIXSemanticRegex { get }
}
// MARK: - Statically encoded semantic level
/// A regex that has statically bound its semantic level
struct StaticSemanticRegexLiteral: RegexLiteralProtocol {
/*
If we had values in type-parameter position, this would be
far easier and more straight-forward to model.
RegexLiteral<SemanticsLevel? = nil>
*/
/// A regex that has statically bound its semantic level
struct ScalarSemanticRegex: RegexComponent {
var level: SemanticsLevel? { .scalar }
}
struct GraphemeSemanticRegex: RegexComponent {
var level: SemanticsLevel? { .graphemeCluster }
}
struct POSIXSemanticRegex: RegexComponent {
var level: SemanticsLevel? { .posix }
}
struct UnspecifiedSemanticRegex: RegexComponent {
var level: SemanticsLevel? { nil }
}
var scalarSemantic: ScalarSemanticRegex { x() }
var graphemeSemantic: GraphemeSemanticRegex { x() }
var posixSemantic: POSIXSemanticRegex { x() }
init(builder: RegexLiteralBuilder) { }
typealias Builder = RegexLiteralBuilder
}
// MARK: - stdlib conformer
/// Stdlib's conformer
struct RegexLiteralBuilder: RegexLiteralBuilderProtocol {
/// Compiler converts literal into a series of calls to this kind of method
mutating func buildCharacterClass_d() -> ASTNodeId { x() }
/// We're done, so partially-compile or otherwise finalize
mutating func finalize() { }
}
/// The produced value for a regex literal. Might end up being same type as
/// `Regex` or `Pattern`, but for now useful to model independently.
struct RegexLiteral: ExpressibleByRegexLiteral {
typealias Builder = RegexLiteralBuilder
/// An explicitly specified semantics level
var level: SemanticsLevel? = nil
init(builder: Builder) {
// TODO: should this be throwing, constant evaluable, or
// some other way to issue diagnostics?
}
}
extension RegexLiteral: RegexComponent, RegexLiteralProtocol {
/// A regex that has finally bound its semantic level (dynamically)
struct BoundSemantic: RegexComponent {
var _level: SemanticsLevel // Bound semantic level
var level: SemanticsLevel? { _level }
}
private func sem(_ level: SemanticsLevel) -> BoundSemantic {
x()
}
var scalarSemantic: BoundSemantic { sem(.scalar) }
var graphemeSemantic: BoundSemantic { sem(.graphemeCluster) }
var posixSemantic: BoundSemantic { sem(.posix) }
}
// ---
internal func x() -> Never { fatalError() }
|
apache-2.0
|
27cb32aac60bc72be72184c300358b83
| 29.61039 | 81 | 0.719771 | 4.621569 | false | false | false | false |
AgentFeeble/pgoapi
|
pgoapi/Classes/Hashing/Random.swift
|
1
|
1596
|
//
// Random.swift
// pgoapi
//
// Created by Rayman Rosevear on 2016/11/15.
// Copyright © 2016 MC. All rights reserved.
//
import Darwin
import Foundation
class Random
{
static func getInt(min: UInt32, range: UInt32) -> UInt32
{
return min + arc4random_uniform(range)
}
static func getDouble(min: Int32, range: Int32) -> Double
{
let d = Double(arc4random()) / Double(UInt32.max)
return Double(min) + d * Double(range)
}
static func choice<T>(_ choices: [T]) -> T
{
assert(choices.count > 0)
let idx = arc4random_uniform(UInt32(choices.count))
return choices[Int(idx)]
}
static func randomBytes(length: Int) -> Data
{
var data = Data(count: length)
let result = data.withUnsafeMutableBytes
{
bytes in
SecRandomCopyBytes(kSecRandomDefault, data.count, bytes)
}
if result != 0
{
print("unable to generate random bytes")
}
return data
}
// from numpy
static func triangular(min: Double, max: Double, mode: Double) -> Double
{
let base = max - min
let minbase = mode - min
let ratio = minbase / base
let minprod = minbase * base
let maxprod = (max - mode) * base
let u = getDouble(min: 0, range: 1)
if u <= ratio
{
return min + sqrt(u * minprod)
}
else
{
return max - sqrt((1.0 - u) * maxprod)
}
}
}
|
apache-2.0
|
8180e11d0a058c28a4e051c606769eda
| 22.455882 | 76 | 0.523511 | 3.967662 | false | false | false | false |
CocoaHeadsConference/CHConferenceApp
|
NSBrazilConf/Extensions/UIViewController+URL.swift
|
1
|
1125
|
//
// SFSafariViewController+URL.swift
// CocoaheadsConf
//
// Created by Bruno Bilescky on 26/11/16.
// Copyright © 2016 Cocoaheads. All rights reserved.
//
import UIKit
extension UIViewController {
func open(url: URL, failure: (title: String, message: String)? = nil) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
} else {
showAlert(title: failure?.title, message: failure?.message)
}
}
func showAlert(title: String?, message: String?) {
var finalTitle = "Atenção"
var finalMessage = "Não foi possível abrir o link desejado."
if let ttl = title,
let msg = message {
finalTitle = ttl
finalMessage = msg
}
let alertController = UIAlertController(title: finalTitle, message: finalMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
|
mit
|
ccd4b44af4f39f358e2601a008c8de3d
| 29.27027 | 113 | 0.613393 | 4.274809 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
swift/example_code/iam/ListPolicies/Tests/ListPoliciesTests/ServiceHandler_Ext.swift
|
1
|
1907
|
/*
Extensions to the `ServiceHandler` class to handle tasks we need
for testing that aren't the purpose of this example.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import AWSIAM
import AWSClientRuntime
import ClientRuntime
import SwiftUtilities
@testable import ServiceHandler
public extension ServiceHandler {
/// Create a new AWS Identity and Access Management (IAM) policy.
///
/// - Parameters:
/// - name: The name of the new policy.
/// - policyDocument: The policy document to assign to the new policy.
///
/// - Returns: A `MyPolicyRecord` describing the new policy.
///
func createPolicy(name: String, policyDocument: String) async throws -> MyPolicyRecord {
let input = CreatePolicyInput(
policyDocument: policyDocument,
policyName: name
)
do {
let output = try await client.createPolicy(input: input)
guard let policy = output.policy else {
throw ServiceHandlerError.noSuchPolicy
}
guard let policyName = policy.policyName,
let policyID = policy.policyId,
let policyARN = policy.arn else {
throw ServiceHandlerError.noSuchPolicy
}
return MyPolicyRecord(name: policyName, id: policyID, arn: policyARN)
} catch {
throw error
}
}
/// Delete an IAM policy.
///
/// - Parameter name: The `MyPolicyRecord` describing the policy to
/// delete.
func deletePolicy(policy: MyPolicyRecord) async throws {
let input = DeletePolicyInput(
policyArn: policy.arn
)
do {
_ = try await client.deletePolicy(input: input)
} catch {
throw error
}
}
}
|
apache-2.0
|
cb8bc5f296c7088257b0bf4f558eeff3
| 29.774194 | 92 | 0.609858 | 4.720297 | false | false | false | false |
omondigeno/ActionablePushMessages
|
Pods/MK/Sources/ImageCardView.swift
|
1
|
16060
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of MaterialKit nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class ImageCardView : MaterialPulseView {
/**
:name: dividerLayer
*/
private var dividerLayer: CAShapeLayer?
/**
:name: dividerColor
*/
public var dividerColor: UIColor? {
didSet {
dividerLayer?.backgroundColor = dividerColor?.CGColor
}
}
/**
:name: divider
*/
public var divider: Bool = true {
didSet {
reloadView()
}
}
/**
:name: dividerInsets
*/
public var dividerInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
dividerInset = MaterialEdgeInsetPresetToValue(dividerInsetPreset)
}
}
/**
:name: dividerInset
*/
public var dividerInset: UIEdgeInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0) {
didSet {
reloadView()
}
}
/**
:name: imageLayer
*/
public private(set) var imageLayer: CAShapeLayer?
/**
:name: image
*/
public override var image: UIImage? {
get {
return nil == imageLayer?.contents ? nil : UIImage(CGImage: imageLayer?.contents as! CGImage)
}
set(value) {
if let v = value {
prepareImageLayer()
imageLayer?.contents = v.CGImage
if 0 == maxImageHeight {
imageLayer?.frame.size.height = image!.size.height / contentsScale
} else {
let h: CGFloat = image!.size.height / contentsScale
imageLayer?.frame.size.height = maxImageHeight < h ? maxImageHeight : h
}
imageLayer?.hidden = false
} else {
imageLayer?.contents = nil
imageLayer?.frame = CGRectZero
imageLayer?.hidden = true
imageLayer?.removeFromSuperlayer()
}
reloadView()
}
}
/**
:name: maxImageHeight
*/
public var maxImageHeight: CGFloat = 0 {
didSet {
if 0 < maxImageHeight {
prepareImageLayer()
let h: CGFloat = image!.size.height / contentsScale
imageLayer?.frame.size.height = maxImageHeight < h ? maxImageHeight : h
} else {
maxImageHeight = 0
imageLayer?.frame.size.height = nil == image ? 0 : image!.size.height / contentsScale
}
reloadView()
}
}
/**
:name: contentsRect
*/
public override var contentsRect: CGRect {
didSet {
prepareImageLayer()
imageLayer?.contentsRect = contentsRect
}
}
/**
:name: contentsCenter
*/
public override var contentsCenter: CGRect {
didSet {
prepareImageLayer()
imageLayer?.contentsCenter = contentsCenter
}
}
/**
:name: contentsScale
*/
public override var contentsScale: CGFloat {
didSet {
prepareImageLayer()
imageLayer?.contentsScale = contentsScale
}
}
/**
:name: contentsGravity
*/
public override var contentsGravity: MaterialGravity {
didSet {
prepareImageLayer()
imageLayer?.contentsGravity = MaterialGravityToString(contentsGravity)
}
}
/**
:name: contentInsets
*/
public var contentInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
contentInset = MaterialEdgeInsetPresetToValue(contentInsetPreset)
}
}
/**
:name: contentInset
*/
public var contentInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.Square2) {
didSet {
reloadView()
}
}
/**
:name: titleLabelInsets
*/
public var titleLabelInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
titleLabelInset = MaterialEdgeInsetPresetToValue(titleLabelInsetPreset)
}
}
/**
:name: titleLabelInset
*/
public var titleLabelInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.Square2) {
didSet {
reloadView()
}
}
/**
:name: titleLabel
*/
public var titleLabel: UILabel? {
didSet {
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
reloadView()
}
}
/**
:name: detailLabelInsets
*/
public var detailLabelInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
detailLabelInset = MaterialEdgeInsetPresetToValue(detailLabelInsetPreset)
}
}
/**
:name: detailLabelInset
*/
public var detailLabelInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.Square2) {
didSet {
reloadView()
}
}
/**
:name: detailLabel
*/
public var detailLabel: UILabel? {
didSet {
detailLabel?.translatesAutoresizingMaskIntoConstraints = false
reloadView()
}
}
/**
:name: leftButtonsInsets
*/
public var leftButtonsInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
leftButtonsInset = MaterialEdgeInsetPresetToValue(leftButtonsInsetPreset)
}
}
/**
:name: leftButtonsInset
*/
public var leftButtonsInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.None) {
didSet {
reloadView()
}
}
/**
:name: leftButtons
*/
public var leftButtons: Array<UIButton>? {
didSet {
if let v = leftButtons {
for b in v {
b.translatesAutoresizingMaskIntoConstraints = false
}
}
reloadView()
}
}
/**
:name: rightButtonsInsets
*/
public var rightButtonsInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
rightButtonsInset = MaterialEdgeInsetPresetToValue(rightButtonsInsetPreset)
}
}
/**
:name: rightButtonsInset
*/
public var rightButtonsInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.None) {
didSet {
reloadView()
}
}
/**
:name: rightButtons
*/
public var rightButtons: Array<UIButton>? {
didSet {
if let v = rightButtons {
for b in v {
b.translatesAutoresizingMaskIntoConstraints = false
}
}
reloadView()
}
}
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
:name: init
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectNull)
}
/**
:name: init
*/
public convenience init?(image: UIImage? = nil, titleLabel: UILabel? = nil, detailLabel: UILabel? = nil, leftButtons: Array<UIButton>? = nil, rightButtons: Array<UIButton>? = nil) {
self.init(frame: CGRectNull)
prepareProperties(image, titleLabel: titleLabel, detailLabel: detailLabel, leftButtons: leftButtons, rightButtons: rightButtons)
}
/**
:name: layoutSublayersOfLayer
*/
public override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
if self.layer == layer {
// image
imageLayer?.frame.size.width = bounds.width
// divider
if divider {
var y: CGFloat = contentInset.bottom + dividerInset.bottom
if 0 < leftButtons?.count {
y += leftButtonsInset.top + leftButtonsInset.bottom + leftButtons![0].frame.height
} else if 0 < rightButtons?.count {
y += rightButtonsInset.top + rightButtonsInset.bottom + rightButtons![0].frame.height
}
if 0 < y {
prepareDivider(bounds.height - y - 0.5, width: bounds.width)
}
} else {
dividerLayer?.removeFromSuperlayer()
dividerLayer = nil
}
}
}
/**
:name: reloadView
*/
public func reloadView() {
// clear constraints so new ones do not conflict
removeConstraints(constraints)
for v in subviews {
v.removeFromSuperview()
}
var verticalFormat: String = "V:|"
var views: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var metrics: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
if nil != imageLayer?.contents {
verticalFormat += "-(insetTop)"
metrics["insetTop"] = imageLayer!.frame.height
} else if nil != titleLabel {
verticalFormat += "-(insetTop)"
metrics["insetTop"] = contentInset.top + titleLabelInset.top
} else if nil != detailLabel {
verticalFormat += "-(insetTop)"
metrics["insetTop"] = contentInset.top + detailLabelInset.top
}
// title
if let v = titleLabel {
addSubview(v)
if nil == imageLayer?.contents {
verticalFormat += "-[titleLabel]"
views["titleLabel"] = v
} else {
MaterialLayout.alignFromTop(self, child: v, top: contentInset.top + titleLabelInset.top)
}
MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + titleLabelInset.left, right: contentInset.right + titleLabelInset.right)
}
// detail
if let v = detailLabel {
addSubview(v)
if nil == imageLayer?.contents && nil != titleLabel {
verticalFormat += "-(insetB)"
metrics["insetB"] = titleLabelInset.bottom + detailLabelInset.top
} else {
metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + detailLabelInset.top
}
verticalFormat += "-[detailLabel]"
views["detailLabel"] = v
MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + detailLabelInset.left, right: contentInset.right + detailLabelInset.right)
}
// leftButtons
if let v = leftButtons {
if 0 < v.count {
var h: String = "H:|"
var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var i: Int = 0
for b in v {
let k: String = "b\(i)"
d[k] = b
if 0 == i++ {
h += "-(left)-"
} else {
h += "-(left_right)-"
}
h += "[\(k)]"
addSubview(b)
MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + leftButtonsInset.bottom)
}
addConstraints(MaterialLayout.constraint(h, options: [], metrics: ["left" : contentInset.left + leftButtonsInset.left, "left_right" : leftButtonsInset.left + leftButtonsInset.right], views: d))
}
}
// rightButtons
if let v = rightButtons {
if 0 < v.count {
var h: String = "H:"
var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var i: Int = v.count - 1
for b in v {
let k: String = "b\(i)"
d[k] = b
h += "[\(k)]"
if 0 == i-- {
h += "-(right)-"
} else {
h += "-(right_left)-"
}
addSubview(b)
MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + rightButtonsInset.bottom)
}
addConstraints(MaterialLayout.constraint(h + "|", options: [], metrics: ["right" : contentInset.right + rightButtonsInset.right, "right_left" : rightButtonsInset.right + rightButtonsInset.left], views: d))
}
}
if nil == imageLayer?.contents {
if 0 < leftButtons?.count {
verticalFormat += "-(insetC)-[button]"
views["button"] = leftButtons![0]
metrics["insetC"] = leftButtonsInset.top
metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom
} else if 0 < rightButtons?.count {
verticalFormat += "-(insetC)-[button]"
views["button"] = rightButtons![0]
metrics["insetC"] = rightButtonsInset.top
metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom
}
if nil != detailLabel {
if nil == metrics["insetC"] {
metrics["insetBottom"] = contentInset.bottom + detailLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
} else {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + detailLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
}
} else if nil != titleLabel {
if nil == metrics["insetC"] {
metrics["insetBottom"] = contentInset.bottom + titleLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
} else {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + titleLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
}
} else if nil != metrics["insetC"] {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + contentInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0)
}
} else if nil != detailLabel {
if 0 < leftButtons?.count {
verticalFormat += "-(insetC)-[button]"
views["button"] = leftButtons![0]
metrics["insetC"] = leftButtonsInset.top
metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom
} else if 0 < rightButtons?.count {
verticalFormat += "-(insetC)-[button]"
views["button"] = rightButtons![0]
metrics["insetC"] = rightButtonsInset.top
metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom
}
if nil == metrics["insetC"] {
metrics["insetBottom"] = contentInset.bottom + detailLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
} else {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + detailLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0)
}
} else {
if 0 < leftButtons?.count {
verticalFormat += "-[button]"
views["button"] = leftButtons![0]
metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + contentInset.top + leftButtonsInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0)
metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom
} else if 0 < rightButtons?.count {
verticalFormat += "-[button]"
views["button"] = rightButtons![0]
metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + contentInset.top + rightButtonsInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0)
metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom
} else {
if translatesAutoresizingMaskIntoConstraints {
addConstraints(MaterialLayout.constraint("V:[view(height)]", options: [], metrics: ["height": imageLayer!.frame.height], views: ["view": self]))
} else {
height = imageLayer!.frame.height
}
}
}
if 0 < views.count {
verticalFormat += "-(insetBottom)-|"
addConstraints(MaterialLayout.constraint(verticalFormat, options: [], metrics: metrics, views: views))
}
}
/**
:name: prepareView
*/
public override func prepareView() {
super.prepareView()
pulseColor = MaterialColor.blueGrey.lighten4
depth = .Depth2
dividerColor = MaterialColor.blueGrey.lighten5
}
/**
:name: prepareImageLayer
*/
internal func prepareImageLayer() {
if nil == imageLayer {
imageLayer = CAShapeLayer()
imageLayer!.masksToBounds = true
imageLayer!.zPosition = 0
visualLayer.addSublayer(imageLayer!)
}
}
/**
:name: prepareDivider
*/
internal func prepareDivider(y: CGFloat, width: CGFloat) {
if nil == dividerLayer {
dividerLayer = CAShapeLayer()
dividerLayer!.zPosition = 0
layer.addSublayer(dividerLayer!)
}
dividerLayer?.backgroundColor = dividerColor?.CGColor
dividerLayer?.frame = CGRectMake(dividerInset.left, y, width - dividerInset.left - dividerInset.right, 1)
}
/**
:name: prepareProperties
*/
internal func prepareProperties(image: UIImage?, titleLabel: UILabel?, detailLabel: UILabel?, leftButtons: Array<UIButton>?, rightButtons: Array<UIButton>?) {
self.image = image
self.titleLabel = titleLabel
self.detailLabel = detailLabel
self.leftButtons = leftButtons
self.rightButtons = rightButtons
}
}
|
apache-2.0
|
d879ccb2e733b3a4d2ba40c6e0e7df72
| 26.40785 | 209 | 0.680635 | 3.717593 | false | false | false | false |
nathawes/swift
|
test/SILGen/same_type_abstraction.swift
|
10
|
2472
|
// RUN: %target-swift-emit-silgen %s | %FileCheck %s
protocol Associated {
associatedtype Assoc
}
struct Abstracted<T: Associated, U: Associated> {
let closure: (T.Assoc) -> U.Assoc
}
struct S1 {}
struct S2 {}
// CHECK-LABEL: sil hidden [ossa] @$s21same_type_abstraction28callClosureWithConcreteTypes{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s{{.*}}TR :
func callClosureWithConcreteTypes<T: Associated, U: Associated>(x: Abstracted<T, U>, arg: S1) -> S2 where T.Assoc == S1, U.Assoc == S2 {
return x.closure(arg)
}
// Problem when a same-type constraint makes an associated type into a tuple
protocol MyProtocol {
associatedtype ReadData
associatedtype Data
func readData() -> ReadData
}
extension MyProtocol where Data == (ReadData, ReadData) {
// CHECK-LABEL: sil hidden [ossa] @$s21same_type_abstraction10MyProtocolPAA8ReadDataQz_AEt0G0RtzrlE07currentG0AE_AEtyF : $@convention(method) <Self where Self : MyProtocol, Self.Data == (Self.ReadData, Self.ReadData)> (@in_guaranteed Self) -> (@out Self.ReadData, @out Self.ReadData)
func currentData() -> Data {
// CHECK: bb0(%0 : $*Self.ReadData, %1 : $*Self.ReadData, %2 : $*Self):
// CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData
// CHECK: apply [[READ_FN]]<Self>(%0, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData
// CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData
// CHECK: apply [[READ_FN]]<Self>(%1, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData
// CHECK: return
return (readData(), readData())
}
}
// Problem with protocol typealiases, which are modeled as same-type
// constraints
protocol Refined : Associated {
associatedtype Key
typealias Assoc = Key
init()
}
extension Refined {
// CHECK-LABEL: sil hidden [ossa] @$s21same_type_abstraction7RefinedPAAE12withElementsx5AssocQz_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self
init(withElements newElements: Key) {
self.init()
}
}
|
apache-2.0
|
8439b422f4231d94f9ff24417aa48b2c
| 42.087719 | 285 | 0.67386 | 3.283422 | false | false | false | false |
ethanneff/iOS-Swift-Segmented-Animated-TableViews
|
SegmentedTableViews/DashboardViewController.swift
|
1
|
2665
|
//
// ViewController.swift
// ToggleStatusBar2
//
// Created by Ethan Neff on 1/28/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import UIKit
class DashboardViewController: UIViewController {
// MARK: properties
@IBOutlet weak var containerHabits: UIView!
@IBOutlet weak var containerGoals: UIView!
@IBOutlet weak var containerMotives: UIView!
var containerCurrentIndex: Int!
var containerCurrentView: UIView!
// MARK: load
override func viewDidLoad() {
super.viewDidLoad()
defaultContainers()
}
func defaultContainers() {
// hide containers
containerGoals.hidden = true
containerMotives.hidden = true
containerHabits.hidden = false
containerCurrentView = containerHabits
containerCurrentIndex = 0
// fix spacing issue with containers
self.automaticallyAdjustsScrollViewInsets = false
}
// MARK: segment navigation
@IBAction func segmentValueChange(segment: UISegmentedControl) {
switch segment.selectedSegmentIndex {
case 0:
navigateContainer(container: containerHabits, index: segment.selectedSegmentIndex)
break
case 1:
navigateContainer(container: containerGoals, index: segment.selectedSegmentIndex)
break
case 2:
navigateContainer(container: containerMotives, index: segment.selectedSegmentIndex)
break
default:
break
}
}
func animateContainer(prevX prevX: CGFloat, nextX: CGFloat, nextContainer: UIView) {
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseOut, animations: { () -> Void in
self.containerCurrentView.frame.origin.x = prevX
nextContainer.frame.origin.x = nextX
}, completion: { (success) -> Void in
self.unloadContainer()
})
}
func navigateContainer(container container: UIView, index: Int) {
loadContainer()
if index < containerCurrentIndex {
// left
container.frame.origin.x = 0 - container.frame.size.width
self.containerCurrentView.frame.origin.x = 0
container.hidden = false
animateContainer(prevX: container.frame.size.width, nextX: 0, nextContainer: container)
} else if index > containerCurrentIndex {
// right
self.containerCurrentView.frame.origin.x = 0
container.frame.origin.x = container.frame.size.width
container.hidden = false
animateContainer(prevX: 0 - self.containerCurrentView.frame.width, nextX: 0, nextContainer: container)
}
// set previous
containerCurrentView = container
containerCurrentIndex = index
}
func loadContainer() {
}
func unloadContainer() {
}
}
|
mit
|
00e79720ce26406b9c6282634270afad
| 27.645161 | 108 | 0.695946 | 4.553846 | false | false | false | false |
jyunderwood/SiriWaveformView-Swift
|
WaveformView/WaveformView/WaveformView.swift
|
2
|
2954
|
//
// WaveformView.swift
// WaveformView
//
// Created by Jonathan on 3/14/15.
// Copyright (c) 2015 Underwood. All rights reserved.
//
import UIKit
import Darwin
let pi = Double.pi
@IBDesignable
public class WaveformView: UIView {
fileprivate var _phase: CGFloat = 0.0
fileprivate var _amplitude: CGFloat = 0.3
@IBInspectable public var waveColor: UIColor = .black
@IBInspectable public var numberOfWaves = 5
@IBInspectable public var primaryWaveLineWidth: CGFloat = 3.0
@IBInspectable public var secondaryWaveLineWidth: CGFloat = 1.0
@IBInspectable public var idleAmplitude: CGFloat = 0.01
@IBInspectable public var frequency: CGFloat = 1.25
@IBInspectable public var density: CGFloat = 5
@IBInspectable public var phaseShift: CGFloat = -0.15
@IBInspectable public var amplitude: CGFloat {
get {
return _amplitude
}
}
public func updateWithLevel(_ level: CGFloat) {
_phase += phaseShift
_amplitude = fmax(level, idleAmplitude)
setNeedsDisplay()
}
override public func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
context.clear(bounds)
backgroundColor?.set()
context.fill(rect)
// Draw multiple sinus waves, with equal phases but altered
// amplitudes, multiplied by a parable function.
for waveNumber in 0...numberOfWaves {
context.setLineWidth((waveNumber == 0 ? primaryWaveLineWidth : secondaryWaveLineWidth))
let halfHeight = bounds.height / 2.0
let width = bounds.width
let mid = width / 2.0
let maxAmplitude = halfHeight - 4.0 // 4 corresponds to twice the stroke width
// Progress is a value between 1.0 and -0.5, determined by the current wave idx,
// which is used to alter the wave's amplitude.
let progress: CGFloat = 1.0 - CGFloat(waveNumber) / CGFloat(numberOfWaves)
let normedAmplitude = (1.5 * progress - 0.5) * amplitude
let multiplier: CGFloat = 1.0
waveColor.withAlphaComponent(multiplier * waveColor.cgColor.alpha).set()
var x: CGFloat = 0.0
while x < width + density {
// Use a parable to scale the sinus wave, that has its peak in the middle of the view.
let scaling = -pow(1 / mid * (x - mid), 2) + 1
let tempCasting: CGFloat = 2.0 * CGFloat(pi) * CGFloat(x / width) * frequency + _phase
let y = scaling * maxAmplitude * normedAmplitude * CGFloat(sinf(Float(tempCasting))) + halfHeight
if x == 0 {
context.move(to: CGPoint(x: x, y: y))
} else {
context.addLine(to: CGPoint(x: x, y: y))
}
x += density
}
context.strokePath()
}
}
}
|
mit
|
8460cba5afe84e0edc60ee1cacfeb40b
| 33.752941 | 113 | 0.597833 | 4.482549 | false | false | false | false |
practicalswift/swift
|
test/IRGen/clang_inline.swift
|
12
|
3319
|
// RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -enable-objc-interop -sdk %S/Inputs -primary-file %s -O -disable-sil-perf-optzns -disable-llvm-optzns -emit-ir -Xcc -fstack-protector -I %t | %FileCheck %s
// RUN: %empty-directory(%t/Empty.framework/Modules/Empty.swiftmodule)
// RUN: %target-swift-frontend -emit-module-path %t/Empty.framework/Modules/Empty.swiftmodule/%target-swiftmodule-name %S/../Inputs/empty.swift -module-name Empty -I %t
// RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s -I %t -F %t -DIMPORT_EMPTY -O -disable-sil-perf-optzns -disable-llvm-optzns -emit-ir -Xcc -fstack-protector -enable-objc-interop | %FileCheck %s
// REQUIRES: CPU=i386 || CPU=x86_64
// REQUIRES: objc_interop
#if IMPORT_EMPTY
import Empty
#endif
import gizmo
// CHECK-LABEL: define hidden swiftcc i64 @"$s12clang_inline16CallStaticInlineC10ReturnZeros5Int64VyF"(%T12clang_inline16CallStaticInlineC* swiftself) {{.*}} {
class CallStaticInline {
func ReturnZero() -> Int64 { return Int64(zero()) }
}
// CHECK-LABEL: define internal i32 @zero()
// CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] {
// CHECK-LABEL: define hidden swiftcc i64 @"$s12clang_inline17CallStaticInline2C10ReturnZeros5Int64VyF"(%T12clang_inline17CallStaticInline2C* swiftself) {{.*}} {
class CallStaticInline2 {
func ReturnZero() -> Int64 { return Int64(wrappedZero()) }
}
// CHECK-LABEL: define internal i32 @wrappedZero()
// CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] {
// CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline10testExterns5Int32VyF"() {{.*}} {
func testExtern() -> CInt {
return wrappedGetInt()
}
// CHECK-LABEL: define internal i32 @wrappedGetInt()
// CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] {
// CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline16testAlwaysInlines5Int32VyF"() {{.*}} {
func testAlwaysInline() -> CInt {
return alwaysInlineNumber()
}
// CHECK-LABEL: define internal i32 @alwaysInlineNumber()
// CHECK-SAME: [[ALWAYS_INLINE:#[0-9]+]] {
// CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline20testInlineRedeclareds5Int32VyF"() {{.*}} {
func testInlineRedeclared() -> CInt {
return zeroRedeclared()
}
// CHECK-LABEL: define internal i32 @zeroRedeclared() #{{[0-9]+}} {
// CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline27testInlineRedeclaredWrappeds5Int32VyF"() {{.*}} {
func testInlineRedeclaredWrapped() -> CInt {
return wrappedZeroRedeclared()
}
// CHECK-LABEL: define internal i32 @wrappedZeroRedeclared() #{{[0-9]+}} {
// CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline22testStaticButNotInlines5Int32VyF"() {{.*}} {
func testStaticButNotInline() -> CInt {
return staticButNotInline()
}
// CHECK-LABEL: define internal i32 @staticButNotInline() #{{[0-9]+}} {
// CHECK-LABEL: define internal i32 @innerZero()
// CHECK-SAME: [[INNER_ZERO_ATTR:#[0-9]+]] {
// CHECK-LABEL: declare i32 @getInt()
// CHECK-SAME: [[GET_INT_ATTR:#[0-9]+]]
// CHECK-DAG: attributes [[INLINEHINT_SSP_UWTABLE]] = { inlinehint optsize ssp {{.*}}}
// CHECK-DAG: attributes [[ALWAYS_INLINE]] = { alwaysinline nounwind optsize ssp
// CHECK-DAG: attributes [[INNER_ZERO_ATTR]] = { inlinehint nounwind optsize ssp
// CHECK-DAG: attributes [[GET_INT_ATTR]] = {
|
apache-2.0
|
8447f78083fff815ed4de0eb08f33291
| 41.012658 | 207 | 0.701115 | 3.241211 | false | true | false | false |
modocache/swift
|
test/decl/var/properties.swift
|
2
|
29468
|
// RUN: %target-parse-verify-swift
func markUsed<T>(_ t: T) {}
struct X { }
var _x: X
class SomeClass {}
func takeTrailingClosure(_ fn: () -> ()) -> Int {}
func takeIntTrailingClosure(_ fn: () -> Int) -> Int {}
//===---
// Stored properties
//===---
var stored_prop_1: Int = 0
var stored_prop_2: Int = takeTrailingClosure {}
//===---
// Computed properties -- basic parsing
//===---
var a1: X {
get {
return _x
}
}
var a2: X {
get {
return _x
}
set {
_x = newValue
}
}
var a3: X {
get {
return _x
}
set(newValue) {
_x = newValue
}
}
var a4: X {
set {
_x = newValue
}
get {
return _x
}
}
var a5: X {
set(newValue) {
_x = newValue
}
get {
return _x
}
}
// Reading/writing properties
func accept_x(_ x: X) { }
func accept_x_inout(_ x: inout X) { }
func test_global_properties(_ x: X) {
accept_x(a1)
accept_x(a2)
accept_x(a3)
accept_x(a4)
accept_x(a5)
a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}}
a2 = x
a3 = x
a4 = x
a5 = x
accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}}
accept_x_inout(&a2)
accept_x_inout(&a3)
accept_x_inout(&a4)
accept_x_inout(&a5)
}
//===--- Implicit 'get'.
var implicitGet1: X {
return _x
}
var implicitGet2: Int {
var zzz = 0
// For the purpose of this test, any other function attribute work as well.
@inline(__always)
func foo() {}
return 0
}
var implicitGet3: Int {
@inline(__always)
func foo() {}
return 0
}
// Here we used apply weak to the getter itself, not to the variable.
var x15: Int {
// For the purpose of this test we need to use an attribute that cannot be
// applied to the getter.
weak
var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}}
return 0
}
// Disambiguated as stored property with a trailing closure in the initializer.
//
// FIXME: QoI could be much better here.
var disambiguateGetSet1a: Int = 0 {
get {} // expected-error {{use of unresolved identifier 'get'}}
}
var disambiguateGetSet1b: Int = 0 {
get { // expected-error {{use of unresolved identifier 'get'}}
return 42
}
}
var disambiguateGetSet1c: Int = 0 {
set {} // expected-error {{use of unresolved identifier 'set'}}
}
var disambiguateGetSet1d: Int = 0 {
set(newValue) {} // expected-error {{use of unresolved identifier 'set'}} expected-error {{use of unresolved identifier 'newValue'}}
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet2() {
func get(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
get {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet2Attr() {
func get(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
get {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet3() {
func set(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
set {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet3Attr() {
func set(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
set {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet4() {
func set(_ x: Int, fn: () -> ()) {}
let newValue: Int = 0
var a: Int = takeTrailingClosure {
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet4Attr() {
func set(_ x: Int, fn: () -> ()) {}
var newValue: Int = 0
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
var disambiguateImplicitGet1: Int = 0 { // expected-error {{cannot call value of non-function type 'Int'}}
return 42
}
var disambiguateImplicitGet2: Int = takeIntTrailingClosure {
return 42
}
//===---
// Observed properties
//===---
class C {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
}
protocol TrivialInit {
init()
}
class CT<T : TrivialInit> {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
var prop5: T? = nil {
didSet { }
}
var prop6: T? = nil {
willSet { }
}
var prop7 = T() {
didSet { }
}
var prop8 = T() {
willSet { }
}
}
//===---
// Parsing problems
//===---
var computed_prop_with_init_1: X {
get {}
} = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}}
// FIXME: Redundant error below
var x2 { // expected-error{{computed property must have an explicit type}} expected-error{{type annotation missing in pattern}}
get {
return _x
}
}
var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}}
get {
return _x
}
}
var duplicateAccessors1: X {
get { // expected-note {{previous definition of getter is here}}
return _x
}
set { // expected-note {{previous definition of setter is here}}
_x = value
}
get { // expected-error {{duplicate definition of getter}}
return _x
}
set(v) { // expected-error {{duplicate definition of setter}}
_x = v
}
}
var duplicateAccessors2: Int = 0 {
willSet { // expected-note {{previous definition of willSet is here}}
}
didSet { // expected-note {{previous definition of didSet is here}}
}
willSet { // expected-error {{duplicate definition of willSet}}
}
didSet { // expected-error {{duplicate definition of didSet}}
}
}
var extraTokensInAccessorBlock1: X {
get {}
a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
}
var extraTokensInAccessorBlock2: X {
get {}
weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
a
}
var extraTokensInAccessorBlock3: X {
get {}
a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
set {}
get {}
}
var extraTokensInAccessorBlock4: X {
get blah wibble // expected-error{{expected '{' to start getter definition}}
}
var extraTokensInAccessorBlock5: X {
set blah wibble // expected-error{{expected '{' to start setter definition}}
}
var extraTokensInAccessorBlock6: X {
willSet blah wibble // expected-error{{expected '{' to start willSet definition}}
}
var extraTokensInAccessorBlock7: X {
didSet blah wibble // expected-error{{expected '{' to start didSet definition}}
}
var extraTokensInAccessorBlock8: X {
foo // expected-error {{use of unresolved identifier 'foo'}}
get {} // expected-error{{use of unresolved identifier 'get'}}
set {} // expected-error{{use of unresolved identifier 'set'}}
}
var extraTokensInAccessorBlock9: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
struct extraTokensInAccessorBlock10 {
var x: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
init() {}
}
var x9: X {
get ( ) { // expected-error{{expected '{' to start getter definition}}
}
}
var x10: X {
set ( : ) { // expected-error{{expected setter parameter name}}
}
get {}
}
var x11 : X {
set { // expected-error{{variable with a setter must also have a getter}}
}
}
var x12: X {
set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start setter definition}}
}
}
var x13: X {} // expected-error {{computed property must have accessors specified}}
// Type checking problems
struct Y { }
var y: Y
var x20: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set {
y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x21: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set(v) {
y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}
var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}, x26: Int
// Properties of struct/enum/extensions
struct S {
var _backed_x: X, _backed_x2: X
var x: X {
get {
return _backed_x
}
mutating
set(v) {
_backed_x = v
}
}
}
extension S {
var x2: X {
get {
return self._backed_x2
}
mutating
set {
_backed_x2 = newValue
}
}
var x3: X {
get {
return self._backed_x2
}
}
}
struct StructWithExtension1 {
var foo: Int
static var fooStatic = 4
}
extension StructWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
static var fooExtStatic = 4
}
class ClassWithExtension1 {
var foo: Int = 0
class var fooStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
extension ClassWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
class var fooExtStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
enum EnumWithExtension1 {
var foo: Int // expected-error {{enums may not contain stored properties}}
static var fooStatic = 4
}
extension EnumWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
static var fooExtStatic = 4
}
protocol ProtocolWithExtension1 {
var foo: Int { get }
static var fooStatic : Int { get }
}
extension ProtocolWithExtension1 {
final var fooExt: Int // expected-error{{extensions may not contain stored properties}}
final static var fooExtStatic = 4 // expected-error{{static stored properties not supported in generic types}}
}
func getS() -> S {
let s: S
return s
}
func test_extension_properties(_ s: inout S, x: inout X) {
accept_x(s.x)
accept_x(s.x2)
accept_x(s.x3)
accept_x(getS().x)
accept_x(getS().x2)
accept_x(getS().x3)
s.x = x
s.x2 = x
s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
x = getS().x
x = getS().x2
x = getS().x3
accept_x_inout(&s.x)
accept_x_inout(&s.x2)
accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
}
extension S {
mutating
func test(other_x: inout X) {
x = other_x
x2 = other_x
x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
other_x = x
other_x = x2
other_x = x3
}
}
// Accessor on non-settable type
struct Aleph {
var b: Beth {
get {
return Beth(c: 1)
}
}
}
struct Beth {
var c: Int
}
func accept_int_inout(_ c: inout Int) { }
func accept_int(_ c: Int) { }
func test_settable_of_nonsettable(_ a: Aleph) {
a.b.c = 1 // expected-error{{cannot assign}}
let x:Int = a.b.c
_ = x
accept_int(a.b.c)
accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}}
}
// TODO: Static properties are only implemented for nongeneric structs yet.
struct MonoStruct {
static var foo: Int = 0
static var (bar, bas): (String, UnicodeScalar) = ("zero", "0")
static var zim: UInt8 {
return 0
}
static var zang = UnicodeScalar("\0")
static var zung: UInt16 {
get {
return 0
}
set {}
}
var a: Double
var b: Double
}
struct MonoStructOneProperty {
static var foo: Int = 22
}
enum MonoEnum {
static var foo: Int = 0
static var zim: UInt8 {
return 0
}
}
struct GenStruct<T> {
static var foo: Int = 0 // expected-error{{static stored properties not supported in generic types}}
}
class MonoClass {
class var foo: Int = 0 // expected-error{{class stored properties not supported in classes; did you mean 'static'?}}
}
protocol Proto {
static var foo: Int { get }
}
func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) {
return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas,
MonoStruct.zim)
}
func staticPropRefThroughInstance(_ foo: MonoStruct) -> Int {
return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}}
}
func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct {
return MonoStruct(a: 1.2, b: 3.4)
}
func getSetStaticProperties() -> (UInt8, UInt16) {
MonoStruct.zim = 12 // expected-error{{cannot assign}}
MonoStruct.zung = 34
return (MonoStruct.zim, MonoStruct.zung)
}
var selfRefTopLevel: Int {
return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}}
}
var selfRefTopLevelSetter: Int {
get {
return 42
}
set {
markUsed(selfRefTopLevelSetter) // no-warning
selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}}
}
}
var selfRefTopLevelSilenced: Int {
get {
return properties.selfRefTopLevelSilenced // no-warning
}
set {
properties.selfRefTopLevelSilenced = newValue // no-warning
}
}
class SelfRefProperties {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}}
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}}
}
}
var silenced: Int {
get {
return self.silenced // no-warning
}
set {
self.silenced = newValue // no-warning
}
}
var someOtherInstance: SelfRefProperties = SelfRefProperties()
var delegatingVar: Int {
// This particular example causes infinite access, but it's easily possible
// for the delegating instance to do something else.
return someOtherInstance.delegatingVar // no-warning
}
}
func selfRefLocal() {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
}
}
}
struct WillSetDidSetProperties {
var a: Int {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var b: Int {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var c: Int {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
var d: Int {
didSet {
markUsed("woot")
}
get { // expected-error {{didSet variable may not also have a get specifier}}
return 4
}
}
var e: Int {
willSet {
markUsed("woot")
}
set { // expected-error {{willSet variable may not also have a set specifier}}
return 4
}
}
var f: Int {
willSet(5) {} // expected-error {{expected willSet parameter name}}
didSet(^) {} // expected-error {{expected didSet parameter name}}
}
var g: Int {
willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start willSet definition}}
}
var h: Int {
didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start didSet definition}}
}
// didSet/willSet with initializers.
// Disambiguate trailing closures.
var disambiguate1: Int = 42 { // simple initializer, simple label
didSet {
markUsed("eek")
}
}
var disambiguate2: Int = 42 { // simple initializer, complex label
willSet(v) {
markUsed("eek")
}
}
var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case.
willSet(v) {
markUsed("eek")
}
}
var disambiguate4: Int = 42 {
willSet {}
}
var disambiguate5: Int = 42 {
didSet {}
}
var disambiguate6: Int = takeTrailingClosure {
@inline(__always)
func f() {}
return ()
}
var inferred1 = 42 {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var inferred2 = 40 {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var inferred3 = 50 {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate1 {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start willSet definition}}
}
}
struct WillSetDidSetDisambiguate1Attr {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start willSet definition}}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate2 {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
struct WillSetDidSetDisambiguate2Attr {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
// No need to disambiguate -- this is clearly a function call.
func willSet(_: () -> Int) {}
struct WillSetDidSetDisambiguate3 {
var x: Int = takeTrailingClosure({
willSet { 42 }
})
}
protocol ProtocolGetSet1 {
var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol ProtocolGetSet2 {
var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol ProtocolGetSet3 {
var a: Int { get }
}
protocol ProtocolGetSet4 {
var a: Int { set } // expected-error {{variable with a setter must also have a getter}}
}
protocol ProtocolGetSet5 {
var a: Int { get set }
}
protocol ProtocolGetSet6 {
var a: Int { set get }
}
protocol ProtocolWillSetDidSet1 {
var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
var globalDidsetWillSet2 : Int = 42 {
didSet {}
}
class Box {
var num: Int
init(num: Int) {
self.num = num
}
}
func double(_ val: inout Int) {
val *= 2
}
class ObservingPropertiesNotMutableInWillSet {
var anotherObj : ObservingPropertiesNotMutableInWillSet
init() {}
var property: Int = 42 {
willSet {
// <rdar://problem/16826319> willSet immutability behavior is incorrect
anotherObj.property = 19 // ok
property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&self.property) // no-warning
}
}
// <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load
var _oldBox : Int
weak var weakProperty: Box? {
willSet {
_oldBox = weakProperty?.num ?? -1
}
}
func localCase() {
var localProperty: Int = 42 {
willSet {
localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}}
}
}
}
}
func doLater(_ fn : () -> ()) {}
// rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet
class MutableInWillSetInClosureClass {
var bounds: Int = 0 {
willSet {
let oldBounds = bounds
doLater { self.bounds = oldBounds }
}
}
}
// <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties
var didSetPropertyTakingOldValue : Int = 0 {
didSet(oldValue) {
markUsed(oldValue)
markUsed(didSetPropertyTakingOldValue)
}
}
// rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types
protocol AbstractPropertyProtocol {
associatedtype Index
var a : Index { get }
}
struct AbstractPropertyStruct<T> : AbstractPropertyProtocol {
typealias Index = T
var a : T
}
// Allow _silgen_name accessors without bodies.
var _silgen_nameGet1: Int {
@_silgen_name("get1") get
set { }
}
var _silgen_nameGet2: Int {
set { }
@_silgen_name("get2") get
}
var _silgen_nameGet3: Int {
@_silgen_name("get3") get
}
var _silgen_nameGetSet: Int {
@_silgen_name("get4") get
@_silgen_name("set4") set
}
// <rdar://problem/16375910> reject observing properties overriding readonly properties
class Base16375910 {
var x : Int { // expected-note {{attempt to override property here}}
return 42
}
var y : Int { // expected-note {{attempt to override property here}}
get { return 4 }
set {}
}
}
class Derived16375910 : Base16375910 {
override init() {}
override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}}
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth
class Derived16382967 : Base16375910 {
override var y : Int {
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16659058> Read-write properties can be made read-only in a property override
class Derived16659058 : Base16375910 {
override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}}
get { return 42 }
}
}
// <rdar://problem/16406886> Observing properties don't work with ownership types
struct PropertiesWithOwnershipTypes {
unowned var p1 : SomeClass {
didSet {
}
}
init(res: SomeClass) {
p1 = res
}
}
// <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers
class Test16608609 {
let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}}
willSet {
}
didSet {
}
}
}
// <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter"
class rdar16941124Base {
var x = 0
}
class rdar16941124Derived : rdar16941124Base {
var y = 0
override var x: Int {
didSet {
y = x + 1 // no warning.
}
}
}
// Overrides of properties with custom ownership.
class OwnershipBase {
class var defaultObject: AnyObject { fatalError("") }
var strongVar: AnyObject? // expected-note{{overridden declaration is here}}
weak var weakVar: AnyObject?
// FIXME: These should be optional to properly test overriding.
unowned var unownedVar: AnyObject = defaultObject
unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}}
}
class OwnershipExplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
}
class OwnershipImplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
}
class OwnershipBadSub : OwnershipBase {
override weak var strongVar: AnyObject? { // expected-error {{cannot override strong property with weak property}}
didSet {}
}
override unowned var weakVar: AnyObject? { // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'AnyObject?'}}
didSet {}
}
override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}}
didSet {}
}
override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override unowned(unsafe) property with unowned property}}
didSet {}
}
}
// <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension
class rdar17391625 {
var prop = 42 // expected-note {{overridden declaration is here}}
}
extension rdar17391625 {
var someStoredVar: Int // expected-error {{extensions may not contain stored properties}}
var someObservedVar: Int { // expected-error {{extensions may not contain stored properties}}
didSet {
}
}
}
class rdar17391625derived : rdar17391625 {
}
extension rdar17391625derived {
// Not a stored property, computed because it is an override.
override var prop: Int { // expected-error {{declarations in extensions cannot override yet}}
didSet {
}
}
}
// <rdar://problem/27671033> Crash when defining property inside an invalid extension
public protocol rdar27671033P {}
struct rdar27671033S<Key, Value> {}
extension rdar27671033S : rdar27671033P where Key == String { // expected-error {{extension of type 'rdar27671033S' with constraints cannot have an inheritance clause}}
let d = rdar27671033S<Int, Int>() // expected-error {{extensions may not contain stored properties}}
}
// <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property
struct r19874152S1 {
let number : Int = 42
}
_ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S1() // Ok
struct r19874152S2 {
var number : Int = 42
}
_ = r19874152S2(number:64) // Ok, property is a var.
_ = r19874152S2() // Ok
struct r19874152S3 { // expected-note {{'init(flavour:)' declared here}}
let number : Int = 42
let flavour : Int
}
_ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavour:')}} {{17-23=flavour}}
_ = r19874152S3(number:64, flavour: 17) // expected-error {{extra argument 'number' in call}}
_ = r19874152S3(flavour: 17) // ok
_ = r19874152S3() // expected-error {{missing argument for parameter 'flavour' in call}}
struct r19874152S4 {
let number : Int? = nil
}
_ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S4() // Ok
struct r19874152S5 {
}
_ = r19874152S5() // ok
struct r19874152S6 {
let (a,b) = (1,2) // Cannot handle implicit synth of this yet.
}
_ = r19874152S5() // ok
// <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:]
class r24314506 { // expected-error {{class 'r24314506' has no initializers}}
var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}}
}
|
apache-2.0
|
44f2f1697b1fa7af108564348ba0f2a1
| 23.783852 | 188 | 0.656 | 3.759153 | false | false | false | false |
huonw/swift
|
test/Sema/exhaustive_switch.swift
|
1
|
33097
|
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-resilience
// RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience -enable-nonfrozen-enum-exhaustivity-diagnostics
func foo(a: Int?, b: Int?) -> Int {
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (.some(_), .some(_)): return 3
}
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (_?, _?): return 3
}
switch Optional<(Int?, Int?)>.some((a, b)) {
case .none: return 1
case let (_, x?)?: return x
case let (x?, _)?: return x
case (.none, .none)?: return 0
}
}
func bar(a: Bool, b: Bool) -> Int {
switch (a, b) {
case (false, false):
return 1
case (true, _):
return 2
case (false, true):
return 3
}
}
enum Result<T> {
case Ok(T)
case Error(Error)
func shouldWork<U>(other: Result<U>) -> Int {
switch (self, other) { // No warning
case (.Ok, .Ok): return 1
case (.Error, .Error): return 2
case (.Error, _): return 3
case (_, .Error): return 4
}
}
}
func overParenthesized() {
// SR-7492: Space projection needs to treat extra paren-patterns explicitly.
let x: Result<(Result<Int>, String)> = .Ok((.Ok(1), "World"))
switch x {
case let .Error(e):
print(e)
case let .Ok((.Error(e), b)):
print(e, b)
case let .Ok((.Ok(a), b)): // No warning here.
print(a, b)
}
}
enum Foo {
case A(Int)
case B(Int)
}
func foo() {
switch (Foo.A(1), Foo.B(1)) {
case (.A(_), .A(_)):
()
case (.B(_), _):
()
case (_, .B(_)):
()
}
switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) {
case (.A(_), _):
break
case (.B(_), (let q, _)?):
print(q)
case (.B(_), nil):
break
}
}
class C {}
enum Bar {
case TheCase(C?)
}
func test(f: Bar) -> Bool {
switch f {
case .TheCase(_?):
return true
case .TheCase(nil):
return false
}
}
func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> {
switch (this, other) { // No warning
case let (.none, w):
return w
case let (w, .none):
return w
case let (.some(e1), .some(e2)):
return .some(e1 && e2)
}
}
enum Threepeat {
case a, b, c
}
func test3(x: Threepeat, y: Threepeat) {
switch (x, y) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.a, .c)'}}
case (.a, .a):
()
case (.b, _):
()
case (.c, _):
()
case (_, .b):
()
}
}
enum A {
case A(Int)
case B(Bool)
case C
case D
}
enum B {
case A
case B
}
func s(a: A, b: B) {
switch (a, b) {
case (.A(_), .A):
break
case (.A(_), .B):
break
case (.B(_), let b):
// expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}}
break
case (.C, _), (.D, _):
break
}
}
enum Grimble {
case A
case B
case C
}
enum Gromble {
case D
case E
}
func doSomething(foo:Grimble, bar:Gromble) {
switch(foo, bar) { // No warning
case (.A, .D):
break
case (.A, .E):
break
case (.B, _):
break
case (.C, _):
break
}
}
enum E {
case A
case B
}
func f(l: E, r: E) {
switch (l, r) {
case (.A, .A):
return
case (.A, _):
return
case (_, .A):
return
case (.B, .B):
return
}
}
enum TestEnum {
case A, B
}
func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) {
switch testEnumTuple {
case (_,.B):
// Matches (.A, .B) and (.B, .B)
break
case (.A,_):
// Matches (.A, .A)
// Would also match (.A, .B) but first case takes precedent
break
case (.B,.A):
// Matches (.B, .A)
break
}
}
func tests(a: Int?, b: String?) {
switch (a, b) {
case let (.some(n), _): print("a: ", n, "?")
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case (.none, _): print("Nothing")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, .none): print("Nothing", "Nothing")
}
}
enum X {
case Empty
case A(Int)
case B(Int)
}
func f(a: X, b: X) {
switch (a, b) {
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
}
}
func f2(a: X, b: X) {
switch (a, b) {
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: ()
}
}
enum XX : Int {
case A
case B
case C
case D
case E
}
func switcheroo(a: XX, b: XX) -> Int {
switch(a, b) { // No warning
case (.A, _) : return 1
case (_, .A) : return 2
case (.C, _) : return 3
case (_, .C) : return 4
case (.B, .B) : return 5
case (.B, .D) : return 6
case (.D, .B) : return 7
case (.B, .E) : return 8
case (.E, .B) : return 9
case (.E, _) : return 10
case (_, .E) : return 11
case (.D, .D) : return 12
default:
print("never hits this:", a, b)
return 13
}
}
enum PatternCasts {
case one(Any)
case two
case three(String)
}
func checkPatternCasts() {
// Pattern casts with this structure shouldn't warn about duplicate cases.
let x: PatternCasts = .one("One")
switch x {
case .one(let s as String): print(s)
case .one: break
case .two: break
case .three: break
}
// But should warn here.
switch x {
case .one(_): print(s)
case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case .two: break
case .three: break
}
// And not here
switch x {
case .one: break
case .two: break
case .three(let s as String?): print(s as Any)
}
}
enum MyNever {}
func ~= (_ : MyNever, _ : MyNever) -> Bool { return true }
func myFatalError() -> MyNever { fatalError() }
func checkUninhabited() {
// Scrutinees of uninhabited type may match any number and kind of patterns
// that Sema is willing to accept at will. After all, it's quite a feat to
// productively inhabit the type of crashing programs.
func test1(x : Never) {
switch x {} // No diagnostic.
}
func test2(x : Never) {
switch (x, x) {} // No diagnostic.
}
func test3(x : MyNever) {
switch x { // No diagnostic.
case myFatalError(): break
case myFatalError(): break
case myFatalError(): break
}
}
}
enum Runcible {
case spoon
case hat
case fork
}
func checkDiagnosticMinimality(x: Runcible?) {
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .hat)'}}
// expected-note@-3 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.spoon, .hat):
break
case (.hat, .spoon):
break
}
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .spoon)'}}
// expected-note@-3 {{add missing case: '(.spoon, .hat)'}}
// expected-note@-4 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.hat, .hat):
break
}
}
enum LargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
}
func notQuiteBigEnough() -> Bool {
switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 110 {{add missing case:}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
}
}
enum OverlyLargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
case case11
}
enum ContainsOverlyLargeEnum {
case one(OverlyLargeSpaceEnum)
case two(OverlyLargeSpaceEnum)
case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum)
}
func quiteBigEnough() -> Bool {
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
case (.case11, .case11): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
@unknown default: return false // expected-note {{remove '@unknown' to handle remaining values}} {{3-12=}}
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
case (.case11, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, .case0): return true
case (_, .case1): return true
case (_, .case2): return true
case (_, .case3): return true
case (_, .case4): return true
case (_, .case5): return true
case (_, .case6): return true
case (_, .case7): return true
case (_, .case8): return true
case (_, .case9): return true
case (_, .case10): return true
case (_, .case11): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case _: return true
}
// No diagnostic
switch ContainsOverlyLargeEnum.one(.case0) {
case .one: return true
case .two: return true
case .three: return true
}
// Make sure we haven't just stopped emitting diagnostics.
switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}} expected-note {{handle unknown values}}
}
}
indirect enum InfinitelySized {
case one
case two
case recur(InfinitelySized)
case mutualRecur(MutuallyRecursive, InfinitelySized)
}
indirect enum MutuallyRecursive {
case one
case two
case recur(MutuallyRecursive)
case mutualRecur(InfinitelySized, MutuallyRecursive)
}
func infinitelySized() -> Bool {
switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
}
func diagnoseDuplicateLiterals() {
let str = "def"
let int = 2
let dbl = 2.5
// No Diagnostics
switch str {
case "abc": break
case "def": break
case "ghi": break
default: break
}
switch str {
case "abc": break
case "def": break // expected-note {{first occurrence of identical literal pattern is here}}
case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "ghi": break
default: break
}
switch str {
case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case "ghi", "jkl": break
case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch str {
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ghi": break
case "def": break
case "abc": break
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someStr() -> String { return "sdlkj" }
let otherStr = "ifnvbnwe"
switch str {
case "sdlkj": break
case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}}
case someStr(): break
case "def": break
case otherStr: break
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ifnvbnwe": break
case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
// No Diagnostics
switch int {
case -2: break
case -1: break
case 0: break
case 1: break
case 2: break
case 3: break
default: break
}
switch int {
case -2: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1: break
case 2: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3: break
default: break
}
switch int {
case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}}
case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
case 4, 5: break
case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}}
// expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3: break
case 17: break // expected-note {{first occurrence of identical literal pattern is here}}
case 4: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 5: break
case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 10: break
case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case 3000: break
case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}}
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someInt() -> Int { return 0x1234 }
let otherInt = 13254
switch int {
case 13254: break
case 3000: break
case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}}
case 0x1234: break
case someInt(): break
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break
case otherInt: break
case 230: break
default: break
}
// No Diagnostics
switch dbl {
case -3.5: break
case -2.5: break
case -1.5: break
case 1.5: break
case 2.5: break
case 3.5: break
default: break
}
switch dbl {
case -3.5: break
case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -1.5: break
case 1.5: break
case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3.5: break
default: break
}
switch dbl {
case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch dbl {
case 1: break
case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 46.2395: break
case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 23452.43: break
default: break
}
func someDouble() -> Double { return 324.4523 }
let otherDouble = 458.2345
switch dbl {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 1.5: break
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 46.2395: break
case someDouble(): break
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case otherDouble: break
case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}}
case 23452.43: break
case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 123453: break
case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
}
func checkLiteralTuples() {
let str1 = "abc"
let str2 = "def"
let int1 = 23
let int2 = 7
let dbl1 = 4.23
let dbl2 = 23.45
// No Diagnostics
switch (str1, str2) {
case ("abc", "def"): break
case ("def", "ghi"): break
case ("ghi", "def"): break
case ("abc", "def"): break // We currently don't catch this
default: break
}
// No Diagnostics
switch (int1, int2) {
case (94, 23): break
case (7, 23): break
case (94, 23): break // We currently don't catch this
case (23, 7): break
default: break
}
// No Diagnostics
switch (dbl1, dbl2) {
case (543.21, 123.45): break
case (543.21, 123.45): break // We currently don't catch this
case (23.45, 4.23): break
case (4.23, 23.45): break
default: break
}
}
func sr6975() {
enum E {
case a, b
}
let e = E.b
switch e {
case .a as E: // expected-warning {{'as' test is always true}}
print("a")
case .b: // Valid!
print("b")
case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}}
print("second a")
}
func foo(_ str: String) -> Int {
switch str { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{do you want to add a default clause?}}
case let (x as Int) as Any:
return x
}
}
_ = foo("wtf")
}
public enum NonExhaustive {
case a, b
}
public enum NonExhaustivePayload {
case a(Int), b(Bool)
}
@_frozen public enum TemporalProxy {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
@_downgrade_exhaustivity_check
case never
}
// Inlinable code is considered "outside" the module and must include a default
// case.
@inlinable
public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}}
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.some(_)'}}
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case .a?: break
case .b?: break
case nil: break
@unknown case _: break
} // no-warning
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, false)'}}
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (value, flag) {
case (.a, _): break
case (.b, false): break
case (_, true): break
@unknown case _: break
} // no-warning
switch (flag, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(false, _)'}}
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (flag, value) {
case (_, .a): break
case (false, .b): break
case (true, _): break
@unknown case _: break
} // no-warning
switch (value, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, _)'}}
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
}
switch (value, value) {
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
@unknown case _: break
} // no-warning
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}}
// expected-note@-1 {{add missing case: '(_, .milliseconds(_))'}}
// expected-note@-2 {{add missing case: '(_, .microseconds(_))'}}
// expected-note@-3 {{add missing case: '(_, .nanoseconds(_))'}}
// expected-note@-4 {{add missing case: '(_, .never)'}}
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}}
// expected-note@-1 {{add missing case: '(_, .seconds(_))'}}
// expected-note@-2 {{add missing case: '(_, .milliseconds(_))'}}
// expected-note@-3 {{add missing case: '(_, .microseconds(_))'}}
// expected-note@-4 {{add missing case: '(_, .nanoseconds(_))'}}
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}}
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
// Test fully-covered switches.
switch interval {
case .seconds, .milliseconds, .microseconds, .nanoseconds: break
case .never: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag {
case true: break
case false: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag as Optional {
case _?: break
case nil: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch (flag, value) {
case (true, _): break
case (false, _): break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
@unknown case _: break
}
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // no-warning
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // no-warning
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
}
enum UnavailableCase {
case a
case b
@available(*, unavailable)
case oopsThisWasABadIdea
}
enum UnavailableCaseOSSpecific {
case a
case b
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
case unavailableOnAllTheseApplePlatforms
#else
@available(*, unavailable)
case dummyCaseForOtherPlatforms
#endif
}
enum UnavailableCaseOSIntroduced {
case a
case b
@available(macOS 50, iOS 50, tvOS 50, watchOS 50, *)
case notYetIntroduced
}
func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) {
switch x {
case .a: break
case .b: break
} // no-error
switch y {
case .a: break
case .b: break
} // no-error
switch z {
case .a: break
case .b: break
case .notYetIntroduced: break
} // no-error
}
|
apache-2.0
|
a6a84664e94eadb947d71683a74b96dc
| 26.017959 | 205 | 0.636372 | 3.61321 | false | false | false | false |
vamsirajendra/firefox-ios
|
Client/Frontend/Browser/OpenSearch.swift
|
3
|
7653
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SWXMLHash
private let TypeSearch = "text/html"
private let TypeSuggest = "application/x-suggestions+json"
private let SearchTermsAllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*-_."
class OpenSearchEngine {
static let PreferredIconSize = 30
let shortName: String
let description: String?
let image: UIImage?
private let searchTemplate: String
private let suggestTemplate: String?
init(shortName: String, description: String?, image: UIImage?, searchTemplate: String, suggestTemplate: String?) {
self.shortName = shortName
self.description = description
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
}
/**
* Returns the search URL for the given query.
*/
func searchURLForQuery(query: String) -> NSURL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/**
* Returns the search suggestion URL for the given query.
*/
func suggestURLForQuery(query: String) -> NSURL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
private func getURLFromTemplate(searchTemplate: String, query: String) -> NSURL? {
let allowedCharacters = NSCharacterSet(charactersInString: SearchTermsAllowedCharacters)
if let escapedQuery = query.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnionWithCharacterSet(NSCharacterSet.URLAllowedCharacterSet())
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnionWithCharacterSet(NSCharacterSet(charactersInString: "{}"))
if let encodedSearchTemplate = searchTemplate.stringByAddingPercentEncodingWithAllowedCharacters(templateAllowedSet) {
let urlString = encodedSearchTemplate.stringByReplacingOccurrencesOfString("{searchTerms}", withString: escapedQuery, options: NSStringCompareOptions.LiteralSearch, range: nil)
return NSURL(string: urlString)
}
}
return nil
}
}
/**
* OpenSearch XML parser.
*
* This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to
* the Firefox-specific search plugin format.
*
* OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1
*/
class OpenSearchParser {
private let pluginMode: Bool
init(pluginMode: Bool) {
self.pluginMode = pluginMode
}
func parse(file: String) -> OpenSearchEngine? {
let data = NSData(contentsOfFile: file)
if data == nil {
print("Invalid search file")
return nil
}
let rootName = pluginMode ? "SearchPlugin" : "OpenSearchDescription"
let docIndexer: XMLIndexer! = SWXMLHash.parse(data!)[rootName][0]
if docIndexer.element == nil {
print("Invalid XML document")
return nil
}
let shortNameIndexer = docIndexer["ShortName"]
if shortNameIndexer.all.count != 1 {
print("ShortName must appear exactly once")
return nil
}
let shortName = shortNameIndexer.element?.text
if shortName == nil {
print("ShortName must contain text")
return nil
}
let descriptionIndexer = docIndexer["Description"]
if !pluginMode && descriptionIndexer.all.count != 1 {
print("Description must appear exactly once")
return nil
}
let description = descriptionIndexer.element?.text
let urlIndexers = docIndexer["Url"].all
if urlIndexers.isEmpty {
print("Url must appear at least once")
return nil
}
var searchTemplate: String!
var suggestTemplate: String?
for urlIndexer in urlIndexers {
let type = urlIndexer.element?.attributes["type"]
if type == nil {
print("Url element requires a type attribute", terminator: "\n")
return nil
}
if type != TypeSearch && type != TypeSuggest {
// Not a supported search type.
continue
}
var template = urlIndexer.element?.attributes["template"]
if template == nil {
print("Url element requires a template attribute", terminator: "\n")
return nil
}
if pluginMode {
let paramIndexers = urlIndexer["Param"].all
if !paramIndexers.isEmpty {
template! += "?"
var firstAdded = false
for paramIndexer in paramIndexers {
if firstAdded {
template! += "&"
} else {
firstAdded = true
}
let name = paramIndexer.element?.attributes["name"]
let value = paramIndexer.element?.attributes["value"]
if name == nil || value == nil {
print("Param element must have name and value attributes", terminator: "\n")
return nil
}
template! += name! + "=" + value!
}
}
}
if type == TypeSearch {
searchTemplate = template
} else {
suggestTemplate = template
}
}
if searchTemplate == nil {
print("Search engine must have a text/html type")
return nil
}
let imageIndexers = docIndexer["Image"].all
var largestImage = 0
var largestImageElement: XMLElement?
// TODO: For now, just use the largest icon.
for imageIndexer in imageIndexers {
let imageWidth = Int(imageIndexer.element?.attributes["width"] ?? "")
let imageHeight = Int(imageIndexer.element?.attributes["height"] ?? "")
// Only accept square images.
if imageWidth != imageHeight {
continue
}
if let imageWidth = imageWidth {
if imageWidth > largestImage {
if imageIndexer.element?.text != nil {
largestImage = imageWidth
largestImageElement = imageIndexer.element
}
}
}
}
var uiImage: UIImage?
if let imageElement = largestImageElement,
imageURL = NSURL(string: imageElement.text!),
imageData = NSData(contentsOfURL: imageURL),
image = UIImage(data: imageData) {
uiImage = image
} else {
print("Error: Invalid search image data")
}
return OpenSearchEngine(shortName: shortName!, description: description, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate)
}
}
|
mpl-2.0
|
a329e92f33fbbe641bf1e1a6a54a29f8
| 34.110092 | 192 | 0.588266 | 5.6773 | false | false | false | false |
Eonil/SignalGraph.Swift
|
Code/Implementations/SetStorage.swift
|
1
|
3185
|
//
// SetStorage.swift
// SG5
//
// Created by Hoon H. on 2015/07/03.
// Copyright (c) 2015 Eonil. All rights reserved.
//
public class SetStorage<T: Hashable>: SetStorageType {
public typealias Element = T
public typealias Snapshot = Set<T>
public typealias Transaction = CollectionTransaction<Set<T>,()>
public typealias OutgoingSignal = TimingSignal<Snapshot, Transaction>
public typealias Signal = OutgoingSignal
///
public init(_ snapshot: Set<T>) {
_snapshot = snapshot
}
deinit {
}
///
public var snapshot: Set<T> {
get {
return _snapshot
}
set(v) {
apply(Transaction([
(_snapshot, (), nil),
(v, nil, ()),
]))
}
}
public func apply(transaction: Transaction) {
_executeWithCastFlagging() {
StateStorageUtility.apply(transaction, to: &_snapshot, relay: _relay)
}
}
public func register(identifier: ObjectIdentifier, handler: Signal->()) {
_executeWithCastFlagging() {
_relay.register(identifier, handler: handler)
handler(HOTFIX_TimingSignalUtility.didBeginStateBySession(_snapshot))
}
}
public func deregister(identifier: ObjectIdentifier) {
_executeWithCastFlagging() {
_relay.handlerForIdentifier(identifier)(HOTFIX_TimingSignalUtility.willEndStateBySession(_snapshot))
_relay.deregister(identifier)
}
}
public func register<S: SensitiveStationType where S.IncomingSignal == OutgoingSignal>(s: S) {
_executeWithCastFlagging() {
register(ObjectIdentifier(s)) { [weak s] in s!.cast($0) }
}
}
public func deregister<S: SensitiveStationType where S.IncomingSignal == OutgoingSignal>(s: S) {
_executeWithCastFlagging() {
deregister(ObjectIdentifier(s))
}
}
///
private typealias _Signal = Signal
private let _relay = Relay<Signal>()
private var _snapshot : Set<T>
private var _isCasting = false
private func _cast(signal: Signal) {
_relay.cast(signal)
}
private func _executeWithCastFlagging(@noescape code: ()->()) {
assert(_isCasting == false, "You cannot call `apply` while some signaling is under casting.")
_isCasting = true
code()
_isCasting = false
}
}
extension SetStorage: EditableSet, CollectionType, SequenceType {
public var count: Int {
get {
return _snapshot.count
}
}
public var startIndex: Snapshot.Index {
get {
return _snapshot.startIndex
}
}
public var endIndex: Snapshot.Index {
get {
return _snapshot.endIndex
}
}
public func generate() -> Snapshot.Generator {
return _snapshot.generate()
}
///
public subscript(index: Snapshot.Index) -> Snapshot.Element {
get {
return _snapshot[index]
}
}
///
public func insert(member: T) {
let tran = CollectionTransaction([([member] as Set<T>, nil, ())])
apply(tran)
}
public func remove(member: T) -> T? {
let ele = _snapshot.contains(member) ? member : nil as T?
let tran = CollectionTransaction([([member] as Set<T>, (), nil)])
apply(tran)
return ele
}
public func removeAll() {
let tran = CollectionTransaction([(_snapshot, (), nil)])
apply(tran)
}
}
private func _singleElementCollectionTransaction<T>(identity: Int, past: T?, future: T?) -> CollectionTransaction<Int,T> {
return CollectionTransaction([])
}
|
mit
|
63de8c470b33105d16771ef081e0a19f
| 21.75 | 122 | 0.68697 | 3.150346 | false | false | false | false |
CoderST/XMLYDemo
|
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/View/FineListenCell.swift
|
1
|
2723
|
//
// FineListenCell.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/26.
// Copyright © 2016年 CoderST. All rights reserved.
// 精品听单
import UIKit
class FineListenCell: UICollectionViewCell {
fileprivate lazy var iconImageView : UIImageView = {
let iconImageView = UIImageView()
iconImageView.contentMode = .scaleAspectFill
return iconImageView
}()
fileprivate lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.numberOfLines = 2
return titleLabel
}()
fileprivate lazy var subtitle : UILabel = {
let subtitle = UILabel()
subtitle.font = UIFont.systemFont(ofSize: 12)
return subtitle
}()
fileprivate lazy var bottomLabel : UILabel = {
let bottomLabel = UILabel()
bottomLabel.font = UIFont.systemFont(ofSize: 12)
return bottomLabel
}()
var fineListenSubItem : HotSubModel?{
didSet{
iconImageView.sd_setImage( with: URL(string: fineListenSubItem?.coverPath ?? ""), placeholderImage: UIImage(named: "placeholder_image"))
titleLabel.text = fineListenSubItem?.title
subtitle.text = fineListenSubItem?.subtitle
bottomLabel.text = fineListenSubItem?.footnote
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(iconImageView)
contentView.addSubview(titleLabel)
contentView.addSubview(subtitle)
contentView.addSubview(bottomLabel)
iconImageView.snp.makeConstraints { (make) in
make.left.top.equalTo(contentView).offset(10)
make.height.width.equalTo(sTingDanItemHeight - 20)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(iconImageView.snp.right).offset(10)
make.right.equalTo(contentView).offset(-10)
make.top.equalTo(iconImageView)
}
subtitle.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.right.equalTo(titleLabel)
make.centerY.equalTo(iconImageView)
}
bottomLabel.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.right.lessThanOrEqualTo(contentView.snp.right).offset(-10)
make.bottom.equalTo(iconImageView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
e20b95f3abf9a1dc0a298eda4e702a38
| 27.547368 | 148 | 0.599926 | 5.107345 | false | false | false | false |
jovito-royeca/Decktracker
|
ios/Decktracker/CardImageTableViewCell.swift
|
1
|
3247
|
//
// CardImageTableViewCell.swift
// Decktracker
//
// Created by Jovit Royeca on 16/07/2016.
// Copyright © 2016 Jovit Royeca. All rights reserved.
//
import UIKit
import CoreData
import SDWebImage
class CardImageTableViewCell: UITableViewCell {
// MARK: Variables
private var _cardOID: NSManagedObjectID?
var cardOID : NSManagedObjectID? {
get {
return _cardOID
}
set (newValue) {
if (_cardOID != newValue) {
_cardOID = newValue
displayCard()
}
}
}
// var backgroundImage:UIImage?
var cardBackImage:UIImage?
// MARK: Outlets
@IBOutlet weak var cardImage: UIImageView!
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// backgroundImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")
cardBackImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/cardback.hq.jpg")
// cardImage.backgroundColor = UIColor(patternImage: backgroundImage!)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: Custom methods
func displayCard() {
if let _cardOID = _cardOID {
let card = CoreDataManager.sharedInstance.mainObjectContext.objectWithID(_cardOID) as! Card
if let urlPath = card.urlPath,
let imageCacheKey = card.imageCacheKey {
if let cachedImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(imageCacheKey) {
cardImage.image = cachedImage
} else {
cardImage.image = cardBackImage
let completedBlock = { (image: UIImage?, data: NSData?, error: NSError?, finished: Bool) -> Void in
if let image = image {
SDImageCache.sharedImageCache().storeImage(image, forKey: imageCacheKey)
performUIUpdatesOnMain {
UIView.transitionWithView(self.cardImage, duration: 1.0, options: .TransitionFlipFromRight, animations: {
self.cardImage.image = image
}, completion: nil)
}
} else {
performUIUpdatesOnMain {
self.cardImage.image = self.cardBackImage
}
}
}
let downloader = SDWebImageDownloader.sharedDownloader()
downloader.downloadImageWithURL(urlPath, options: .UseNSURLCache, progress: nil, completed: completedBlock)
}
} else {
cardImage.image = cardBackImage
}
} else {
cardImage.image = cardBackImage
}
}
}
|
apache-2.0
|
966f569464b8cc4e646a71b4c3d5384d
| 34.67033 | 137 | 0.532039 | 5.869801 | false | false | false | false |
Brightify/Cuckoo
|
Generator/Source/CuckooGeneratorFramework/Tokens/Import.swift
|
2
|
1337
|
//
// Import.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 17.06.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public struct Import: Token {
public enum Importee: CustomStringConvertible {
case library(name: String)
case component(componentType: String?, library: String, name: String)
public var description: String {
switch self {
case .library(let name):
return name
case .component(let componentType, let library, let name):
return [componentType, "\(library).\(name)"].compactMap { $0 }.joined(separator: " ")
}
}
}
public let range: CountableRange<Int>
public let importee: Importee
public func isEqual(to other: Token) -> Bool {
guard let other = other as? Import, self.range == other.range else { return false }
switch (self.importee, other.importee) {
case (.library(let lhsName), .library(let rhsName)):
return lhsName == rhsName
case (.component(let lhsImportType, let lhsLibrary, let lhsName), .component(let rhsImportType, let rhsLibrary, let rhsName)):
return lhsImportType == rhsImportType && lhsLibrary == rhsLibrary && lhsName == rhsName
default:
return false
}
}
}
|
mit
|
d59dc5151acca40d28c8c5b6e3f11088
| 34.157895 | 134 | 0.614521 | 4.438538 | false | false | false | false |
quire-io/SwiftyChrono
|
Sources/Parsers/DE/DEMonthNameLittleEndianParser.swift
|
1
|
4425
|
//
// DEMonthNameLittleEndianParser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 2/9/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
private let PATTERN = "(\\W|^)" +
"(?:vo(?:n|m)|am\\s*?)?" +
"(?:(\(DE_WEEKDAY_WORDS_PATTERN))\\s*,?\\s*)?(?:den\\s*)?" +
"(([0-9]{1,2})(?:\\.)?|\(DE_ORDINAL_WORDS_PATTERN))" +
"(?:\\s*" +
"(?:bis|\\-|\\–|\\s)\\s*" +
"(([0-9]{1,2})(?:\\.)?|\(DE_ORDINAL_WORDS_PATTERN))" +
")?\\s*(?:of)?\\s*" +
"(\(DE_MONTH_OFFSET_PATTERN))" +
"(?:" +
",?\\s*([0-9]{1,4}(?![^\\s]\\d))" +
"(\\s*(?:n\\.?\\s?chr\\.?|v\\.?\\s?chr\\.?))?" +
")?" +
"(?=\\W|$)"
private let weekdayGroup = 2
private let dateGroup = 3
private let dateNumGroup = 4
private let dateToGroup = 5
private let dateToNumGroup = 6
private let monthNameGroup = 7
private let yearGroup = 8
private let yearBeGroup = 9
public class DEMonthNameLittleEndianParser: Parser {
override var pattern: String { return PATTERN }
override var language: Language { return .german }
override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match)
var result = ParsedResult(ref: ref, index: index, text: matchText)
let month = DE_MONTH_OFFSET[match.string(from: text, atRangeIndex: monthNameGroup).lowercased()]!
let day = match.isNotEmpty(atRangeIndex: dateNumGroup) ?
Int(match.string(from: text, atRangeIndex: dateNumGroup))! :
DE_ORDINAL_WORDS[match.string(from: text, atRangeIndex: dateGroup).trimmed().lowercased()]!
if match.isNotEmpty(atRangeIndex: yearGroup) {
var year = Int(match.string(from: text, atRangeIndex: yearGroup))!
if match.isNotEmpty(atRangeIndex: yearBeGroup) {
let yearBe = match.string(from: text, atRangeIndex: yearBeGroup)
if NSRegularExpression.isMatch(forPattern: "v", in: yearBe) {
// Before Christ
year = -year
}
} else if year < 10 {
// require single digit years to always have BC/AD
return nil
} else if year < 100 {
year += 2000
}
result.start.assign(.day, value: day)
result.start.assign(.month, value: month)
result.start.assign(.year, value: year)
} else {
//Find the most appropriated year
var refMoment = ref
refMoment = refMoment.setOrAdded(month, .month)
refMoment = refMoment.setOrAdded(day, .day)
refMoment = refMoment.setOrAdded(ref.year, .year)
let nextYear = refMoment.added(1, .year)
let lastYear = refMoment.added(-1, .year)
if abs(nextYear.differenceOfTimeInterval(to: ref)) < abs(refMoment.differenceOfTimeInterval(to: ref)) {
refMoment = nextYear
} else if abs(lastYear.differenceOfTimeInterval(to: ref)) < abs(refMoment.differenceOfTimeInterval(to: ref)) {
refMoment = lastYear
}
result.start.assign(.day, value: day)
result.start.assign(.month, value: month)
result.start.imply(.year, to: refMoment.year)
}
// Weekday component
if match.isNotEmpty(atRangeIndex: weekdayGroup) {
let weekday = DE_WEEKDAY_OFFSET[match.string(from: text, atRangeIndex: weekdayGroup).lowercased()]
result.start.assign(.weekday, value: weekday)
}
// Text can be 'range' value. Such as '12 - 13 January 2012'
if match.isNotEmpty(atRangeIndex: dateToGroup) {
let endDate = match.isNotEmpty(atRangeIndex: dateToNumGroup) ?
Int(match.string(from: text, atRangeIndex: dateToNumGroup)) :
DE_ORDINAL_WORDS[match.string(from: text, atRangeIndex: dateToGroup).trimmed().replacingOccurrences(of: "-", with: " ").lowercased()]
result.end = result.start.clone()
result.end?.assign(.day, value: endDate)
}
result.tags[.deMonthNameLittleEndianParser] = true
return result
}
}
|
mit
|
62a139f0e9d3dfbe358cfa6d81703ac6
| 39.568807 | 149 | 0.567616 | 4.038356 | false | false | false | false |
KagasiraBunJee/TryHard
|
TryHard/THImageProcessingVC.swift
|
1
|
1405
|
//
// THImageProcessingVC.swift
// TryHard
//
// Created by Sergey on 6/17/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
import SDWebImage
class THImageProcessingVC: UIViewController {
@IBOutlet weak var imageBefore: UIImageView!
private var image:UIImage?
var url = NSURL(string: "https://onepagelove.com/wp-content/uploads/2016/03/opl-big-5.jpg")!
override func viewDidLoad() {
super.viewDidLoad()
SDWebImageManager.sharedManager().downloadImageWithURL(url, options: .RefreshCached, progress: nil) { (image, error, cacheType, complete, url) in
if complete {
self.image = image
}
}
}
//MARK:- IBAction
@IBAction func downloadAction(sender: AnyObject) {
imageBefore.image = image
}
@IBAction func processAction(sender: AnyObject) {
let image = self.imageBefore.image!.copy() as! UIImage
// let bounds = (image.textBoundsV2() as! [NSValue]).map { (value) -> CGRect in
// return value.CGRectValue()
// }
//
// let rectedImage = image.drawRects(bounds, color: UIColor.redColor())
imageBefore.image = image.textDetectBetterV2()
print(image.textBoundsV2())
}
}
|
mit
|
10926ce23fc728224683b90bd196c571
| 25 | 153 | 0.580484 | 4.373832 | false | false | false | false |
stripe/stripe-ios
|
IntegrationTester/IntegrationTester/Views/PaymentMethodWithContactInfoView.swift
|
1
|
1989
|
//
// OXXOView.swift
// IntegrationTester
//
// Created by David Estes on 2/11/21.
//
import SwiftUI
import Stripe
struct PaymentMethodWithContactInfoView: View {
let integrationMethod: IntegrationMethod
@StateObject var model = MyPIModel()
@State var isConfirmingPayment = false
@State var name: String = "Jane Diaz"
@State var email: String = "[email protected]"
var body: some View {
VStack {
TextField("Name", text: $name)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.textContentType(.name)
TextField("Email", text: $email)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.textContentType(.emailAddress)
if let paymentIntent = model.paymentIntentParams {
Button("Buy") {
paymentIntent.paymentMethodParams = integrationMethod.defaultPaymentMethodParams
let billingDetails = STPPaymentMethodBillingDetails()
billingDetails.name = name
billingDetails.email = email
paymentIntent.paymentMethodParams?.billingDetails = billingDetails
isConfirmingPayment = true
}.paymentConfirmationSheet(isConfirmingPayment: $isConfirmingPayment,
paymentIntentParams: paymentIntent,
onCompletion: model.onCompletion)
.disabled(isConfirmingPayment || name.isEmpty || email.isEmpty)
} else {
ProgressView()
}
if let paymentStatus = model.paymentStatus {
PaymentHandlerStatusView(actionStatus: paymentStatus, lastPaymentError: model.lastPaymentError)
}
}.onAppear {
model.integrationMethod = integrationMethod
model.preparePaymentIntent()
}
}
}
struct PaymentMethodWithContactInfoView_Preview : PreviewProvider {
static var previews: some View {
PaymentMethodWithContactInfoView(integrationMethod: .oxxo)
}
}
|
mit
|
126ce4c479152ccd0fb4c3d259f4281a
| 33.894737 | 105 | 0.65812 | 5.206806 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Random Value Generation/Characteristics/ConferenceDayCharacteristics+RandomValueProviding.swift
|
1
|
622
|
import EurofurenceModel
import Foundation
import TestUtilities
extension ConferenceDayCharacteristics: RandomValueProviding {
public static var random: ConferenceDayCharacteristics {
let randomDate = Date.random
var components = Calendar.current.dateComponents(in: .current, from: randomDate)
components.hour = 0
components.minute = 0
components.second = 0
components.nanosecond = 0
let normalizedDate = components.date.unsafelyUnwrapped
return ConferenceDayCharacteristics(identifier: .random, date: normalizedDate)
}
}
|
mit
|
b2f6d5eff12e13bbbeebbaadd933fa04
| 30.1 | 88 | 0.702572 | 5.759259 | false | false | false | false |
ethanneff/iOS-Swift-Animated-Reorder-And-Indent
|
NotesApp/User.swift
|
1
|
2196
|
//
// User.swift
// NotesApp
//
// Created by Ethan Neff on 4/4/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import Foundation
class User: NSObject, NSCoding {
// PROPERTIES
var email: String
var password: String
var tasks: [Task]
override var description: String {
return "\(email)"
}
// INIT
init?(email: String, password: String, tasks: [Task]) {
self.email = email
self.password = password
self.tasks = tasks
super.init()
if email.isEmpty || password.isEmpty {
return nil
}
}
// SAVE
struct PropertyKey {
static let email = "email"
static let password = "password"
static let tasks = "tasks"
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(email, forKey: PropertyKey.email)
aCoder.encodeObject(password, forKey: PropertyKey.password)
aCoder.encodeObject(tasks, forKey: PropertyKey.tasks)
}
required convenience init?(coder aDecoder: NSCoder) {
let email = aDecoder.decodeObjectForKey(PropertyKey.email) as! String
let password = aDecoder.decodeObjectForKey(PropertyKey.password) as! String
let tasks = aDecoder.decodeObjectForKey(PropertyKey.tasks) as! [Task]
self.init(email: email, password: password, tasks: tasks)
}
// ACCESS
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("user")
static func get(completion completion: (user: User?) -> ()) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
if let data = NSKeyedUnarchiver.unarchiveObjectWithFile(User.ArchiveURL.path!) as? User {
completion(user: data)
} else {
completion(user: nil)
}
})
}
static func set(data data: User, completion: (success: Bool) -> ()) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(data, toFile: User.ArchiveURL.path!)
if !isSuccessfulSave {
completion(success: false)
} else {
completion(success: true)
}
})
}
}
|
mit
|
0a74010af03617ce30a623bd5ce7d91d
| 27.519481 | 121 | 0.68246 | 4.221154 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/BaseTest/BaseTest/ProtocolPragmming/Event.swift
|
1
|
690
|
//
// Event.swift
// BaseTest
//
// Created by wuyp on 2017/9/14.
// Copyright © 2017年 raymond. All rights reserved.
//
import Foundation
struct User {
var name: String
var age: Int
init?(json: [String : Any]) {
// if let name = json["name"] as? String,
// let age = json["age"] as? Int {
// self.init(name: name, age: age)
// }
guard let name = json["name"] as? String,
let age = json["age"] as? Int else {
return nil
}
self.init(name: name, age: age)
}
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
|
apache-2.0
|
47a07885b074c59791b5c478169c61c9
| 19.818182 | 51 | 0.481805 | 3.505102 | false | false | false | false |
jduquennoy/Log4swift
|
Log4swiftTests/Appenders/AppleUnifiedLoggerAppenderTests.swift
|
1
|
7582
|
//
// SystemLoggerAppenderTests.swift
// log4swiftTests
//
// Created by Jérôme Duquennoy on 24/10/2017.
// Copyright © 2017 jerome. All rights reserved.
//
import XCTest
import Foundation
@testable import Log4swift
import os.log
@available(iOS 10.0, macOS 10.12, *)
class AppleUnifiedLoggerAppenderTests: XCTestCase {
let testLoggerName = "Log4swift.tests.systemLoggerAppender"
func testLogWithOffLevelDoesNotLog() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
appender.thresholdLevel = .Trace
// Execute
appender.log(logMessage, level: LogLevel.Off, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 0)
}
func testLoggingTwiceWithTheSameLoggerNameLogsMessagesCorrectly() throws {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Info, info: infoDictionary)
appender.log(logMessage, level: LogLevel.Info, info: infoDictionary)
let foundMessages = try self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 2)
}
func testCategoryIsDashIfNoLoggerNameIsProvided() {
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Info, info: LogInfoDictionary())
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].category, "-")
}
}
func testLogDebugMessageAsDebug() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Debug, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].messageType, "Debug")
XCTAssertEqual(foundMessages[0].category, infoDictionary[LogInfoKeys.LoggerName])
}
}
func testLogInfoMessageAsInfo() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Info, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].messageType, "Info")
XCTAssertEqual(foundMessages[0].category, infoDictionary[LogInfoKeys.LoggerName])
}
}
func testLogWarningMessageAsDefault() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Warning, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].messageType, "Default")
XCTAssertEqual(foundMessages[0].category, infoDictionary[LogInfoKeys.LoggerName])
}
}
func testLogErrorMessageAsError() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test info message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Error, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].messageType, "Error")
XCTAssertEqual(foundMessages[0].category, infoDictionary[LogInfoKeys.LoggerName])
}
}
func testLogFatalMessageAsFault() {
let infoDictionary = [LogInfoKeys.LoggerName: testLoggerName]
let appender = AppleUnifiedLoggerAppender("testAppender")
let logMessage = "Test fatal message " + UUID().uuidString
// Execute
appender.log(logMessage, level: LogLevel.Fatal, info: infoDictionary)
let foundMessages = try! self.findLogMessage(logMessage)
XCTAssertEqual(foundMessages.count, 1)
if foundMessages.count > 0 {
XCTAssertEqual(foundMessages[0].messageType, "Fault")
XCTAssertEqual(foundMessages[0].category, infoDictionary[LogInfoKeys.LoggerName])
}
}
private func findLogMessage(_ text: String) throws -> [SystemLogMessage] {
// The log system is async, so the log might appear after a small delay.
// We loop with a small wait to work that around.
// So this method can take several seconds to run, in the worst case (no log message found)
var triesLeft = 1
var foundMessages = [SystemLogMessage]()
print("searching log '\(text)'")
repeat {
// log show --predicate "eventMessage = 'message'" --last "1m" --style json --info --debug
// escape ' with \
let protectedMessage = text.replacingOccurrences(of: "'", with: "\\'")
print("cmd = log \(["show", "--predicate", "eventMessage == '\(protectedMessage)'", "--last", "1m", "--style", "json", "--info", "--debug"].joined(separator: " "))")
let jsonData = self.execCommand(command: "log", args: ["show", "--predicate", "eventMessage == '\(protectedMessage)'", "--last", "1m", "--style", "json", "--info", "--debug"])
let jsonDecoder = JSONDecoder()
foundMessages = try jsonDecoder.decode(Array<SystemLogMessage>.self, from: jsonData)
if foundMessages.count == 0 {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
}
triesLeft -= 1
} while(triesLeft > 0 && foundMessages.isEmpty)
return foundMessages
}
private func execCommand(command: String, args: [String]) -> Data {
if !command.hasPrefix("/") {
let commandFullPathData = execCommand(command: "/usr/bin/which", args: [command])
let commandFullPath = String(data: commandFullPathData, encoding: String.Encoding.utf8)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return execCommand(command: commandFullPath, args: args)
}
let proc = Process()
proc.launchPath = command
proc.arguments = args
let pipe = Pipe()
proc.standardOutput = pipe
proc.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return data
}
}
struct SystemLogMessage: Decodable {
let category: String
let processImageUUID: String
let processUniqueID: UInt? // depending on the OS version, the process uniqueID might not appear (it does not on 10.13)
let threadID: UInt
let timestamp: String
let traceID: Int
let messageType: String
let activityID: UInt64?
let processID: UInt
let machTimestamp: UInt64
let timezoneName: String
let subsystem: String
let senderProgramCounter: UInt
let eventMessage: String
let senderImageUUID: String
let processImagePath: String
let senderImagePath: String
}
|
apache-2.0
|
571e0e60e89ccf976d18a9d0c115c868
| 37.085427 | 181 | 0.712231 | 4.437354 | false | true | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/Swiftz/Sources/Swiftz/Proxy.swift
|
3
|
5079
|
//
// Proxy.swift
// Swiftz
//
// Created by Robert Widmann on 7/20/15.
// Copyright © 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// A `Proxy` type is used to bear witness to some type variable. It is used
/// when you want to pass around proxy values for doing things like modelling
/// type applications or faking GADTs as in
/// ~(https://gist.github.com/jckarter/cff22c8b1dcb066eaeb2).
public struct Proxy<T> { public init() {} }
extension Proxy : Equatable {}
public func == <T>(_ : Proxy<T>, _ : Proxy<T>) -> Bool {
return true
}
public func != <T>(_ : Proxy<T>, _ : Proxy<T>) -> Bool {
return false
}
extension Proxy : CustomStringConvertible {
public var description : String {
return "Proxy"
}
}
extension Proxy : Bounded {
public static func minBound() -> Proxy<T> {
return Proxy()
}
public static func maxBound() -> Proxy<T> {
return Proxy()
}
}
extension Proxy : Semigroup {
public func op(_ : Proxy<T>) -> Proxy<T> {
return Proxy()
}
}
extension Proxy : Monoid {
public static var mempty : Proxy<T> {
return Proxy()
}
}
extension Proxy /*: Functor*/ {
public typealias A = T
public typealias B = Any
public typealias FB = Proxy<B>
public func fmap<B>(_ f : (A) -> B) -> Proxy<B> {
return Proxy<B>()
}
}
public func <^> <A, B>(_ f : (A) -> B, l : Proxy<A>) -> Proxy<B> {
return Proxy()
}
extension Proxy /*: Pointed*/ {
public static func pure(_ : A) -> Proxy<T> {
return Proxy()
}
}
extension Proxy /*: Applicative*/ {
public typealias FAB = Proxy<(A) -> B>
public func ap<B>(_ f : Proxy<(A) -> B>) -> Proxy<B> {
return Proxy<B>()
}
}
extension Proxy /*: Cartesian*/ {
public typealias FTOP = Proxy<()>
public typealias FTAB = Proxy<(A, B)>
public typealias FTABC = Proxy<(A, B, C)>
public typealias FTABCD = Proxy<(A, B, C, D)>
public static var unit : Proxy<()> { return Proxy<()>() }
public func product<B>(_ : Proxy<B>) -> Proxy<(A, B)> {
return Proxy<(A, B)>()
}
public func product<B, C>(_ r : Proxy<B>, _ s : Proxy<C>) -> Proxy<(A, B, C)> {
return Proxy<(A, B, C)>()
}
public func product<B, C, D>(_ r : Proxy<B>, _ s : Proxy<C>, _ t : Proxy<D>) -> Proxy<(A, B, C, D)> {
return Proxy<(A, B, C, D)>()
}
}
extension Proxy /*: ApplicativeOps*/ {
public typealias C = Any
public typealias FC = Proxy<C>
public typealias D = Any
public typealias FD = Proxy<D>
public static func liftA<B>(_ f : @escaping (A) -> B) -> (Proxy<A>) -> Proxy<B> {
return { a in Proxy<(A) -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Proxy<A>) -> (Proxy<B>) -> Proxy<C> {
return { a in { b in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Proxy<A>) -> (Proxy<B>) -> (Proxy<C>) -> Proxy<D> {
return { a in { b in { c in f <^> a <*> b <*> c } } }
}
}
public func <*> <A, B>(_ f : Proxy<((A) -> B)>, l : Proxy<A>) -> Proxy<B> {
return Proxy()
}
extension Proxy /*: Monad*/ {
public func bind<B>(_ f : (A) -> Proxy<B>) -> Proxy<T> {
return Proxy()
}
}
public func >>- <A, B>(l : Proxy<A>, f : (A) -> Proxy<B>) -> Proxy<B> {
return Proxy()
}
extension Proxy /*: MonadOps*/ {
public static func liftM<B>(_ f : (A) -> B) -> (Proxy<A>) -> Proxy<B> {
return { m1 in Proxy<B>() }
}
public static func liftM2<B, C>(_ f : (A) -> (B) -> C) -> (Proxy<A>) -> (Proxy<B>) -> Proxy<C> {
return { m1 in { m2 in Proxy<C>() } }
}
public static func liftM3<B, C, D>(_ f : (A) -> (B) -> (C) -> D) -> (Proxy<A>) -> (Proxy<B>) -> (Proxy<C>) -> Proxy<D> {
return { m1 in { m2 in { m3 in Proxy<D>() } } }
}
}
public func >>->> <A, B, C>(_ f : @escaping (A) -> Proxy<B>, g : @escaping (B) -> Proxy<C>) -> ((A) -> Proxy<C>) {
return { x in f(x) >>- g }
}
public func <<-<< <A, B, C>(g : @escaping (B) -> Proxy<C>, f : @escaping (A) -> Proxy<B>) -> ((A) -> Proxy<C>) {
return f >>->> g
}
extension Proxy /*: MonadZip*/ {
public typealias FTABL = Proxy<(A, B)>
public func mzip<B>(_ : Proxy<T>) -> Proxy<(A, B)> {
return Proxy<(A, B)>()
}
public func mzipWith<B, C>(_ : Proxy<B>, _ : (A) -> (B) -> C) -> Proxy<C> {
return Proxy<C>()
}
public static func munzip<B>(_ : Proxy<(A, B)>) -> (Proxy<T>, Proxy<T>) {
return (Proxy(), Proxy())
}
}
extension Proxy : Copointed {
public func extract() -> A {
fatalError()
}
}
extension Proxy : Comonad {
public typealias FFA = Proxy<Proxy<T>>
public func duplicate() -> Proxy<Proxy<T>> {
return Proxy<Proxy<T>>()
}
public func extend<B>(_ fab : (Proxy<T>) -> B) -> Proxy<B> {
return Proxy<B>()
}
}
/// Uses the proxy to bear witness to the type of the first argument. Useful in cases where the
/// type is too polymorphic for the compiler to infer.
public func asProxyTypeOf<T>(x : T, _ proxy : Proxy<T>) -> T {
return const(x)(proxy)
}
public func sequence<A>(_ ms : [Proxy<A>]) -> Proxy<[A]> {
return ms.reduce(Proxy<[A]>.pure([]), { n, m in
return n.bind { xs in
return m.bind { x in
return Proxy<[A]>.pure(xs + [x])
}
}
})
}
|
apache-2.0
|
07e02d573c13a16de0e4dbd98cf9f9bc
| 23.180952 | 131 | 0.564199 | 2.741901 | false | false | false | false |
STShenZhaoliang/Swift2Guide
|
Swift2Guide/Swift100Tips/Swift100Tips/AnyController.swift
|
1
|
1118
|
//
// AnyController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/26.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class AnyController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swiftInt: Int = 1
let swiftString: String = "miao"
var array: [AnyObject] = []
array.append(swiftInt)
array.append(swiftString)
// 显式地声明了需要 AnyObject,编译器认为我们需要的的是 Cocoa 类型而非原生类型,而帮我们进行了自动的转换。
}
}
//AnyObject 可以代表任何 class 类型的实例
//Any 可以表示任意类型,甚至包括方法 (func) 类型
/*
func someMethod() -> AnyObject? {
// ...
// 返回一个 AnyObject?,等价于在 Objective-C 中返回一个 id
return result
}
let anyObject: AnyObject? = SomeClass.someMethod()
if let someInstance = anyObject as? SomeRealClass {
// ...
// 这里我们拿到了具体 SomeRealClass 的实例
someInstance.funcOfSomeRealClass()
}
*/
|
mit
|
e7a67df0e53e151238c8d7e1339aea13
| 19.333333 | 71 | 0.624044 | 3.519231 | false | false | false | false |
bwitt2/rendezvous
|
Rendezvous/MapViewController.swift
|
1
|
6916
|
//
// MapViewController.swift
// Rendezvous
//
//I cant seem to get the locationManager.location object to update frequently
//we need to find a way to be notified if there is a change in current location so that we can keep the camera centered on our current lcoation
import UIKit
// add this below GMSMapViewDelegate
class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate{
//Outlets
@IBOutlet weak var mapView: GMSMapView?
@IBOutlet weak var addressInputField: UITextField!
@IBOutlet weak var placesObject: GooglePlacesAutoComplete!
//Member Variables
var container: ContainerViewController! //Holds managing container
var firstLocationUpdate: Bool?
var locationManager = CLLocationManager()
var geocoder: Geocoder = Geocoder()
var currentLocationIcon: CurrentLocationIcon!
var markers: NSMutableArray = NSMutableArray()
//Actions
@IBAction func editingChanged(sender: AnyObject) {
placesObject.search(addressInputField.text)
placesObject.reloadData()
}
@IBAction func postEventBtn(sender: AnyObject) {
println("Current Location Post")
}
@IBAction func feedBtn(sender: AnyObject) {
container.scrollView!.scrollRectToVisible(container.feedView.view.frame, animated: true)
}
@IBAction func swipeRight(sender: AnyObject) {
container.scrollView!.scrollRectToVisible(container.postView.view.frame, animated: true)
}
@IBAction func swipeLeft(sender: AnyObject) {
container.scrollView!.scrollRectToVisible(container.feedView.view.frame, animated: true)
}
//Overrides
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
self.addressInputField.delegate = self;
addressInputField.userInteractionEnabled = true
mapView?.addSubview(placesObject)
placesObject.delegate = placesObject
placesObject.dataSource = placesObject
placesObject.mapView = self
addCurrentLocationIcon()
locationManager.startUpdatingLocation()
startMaps()
loadMarkers()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
//does not recognize a touch if the map is what is being touched
self.view.endEditing(true)
}
//Optionals
func textFieldShouldReturn(textField: UITextField) -> Bool {
//Currently crashing program
self.view.endEditing(true)
geocoder.getCoordinates(textField.text)
println(textField.text)
textField.text = ""
textField.placeholder = "Where's your next rendezvous?"
if(locationManager.location != nil){
print("lat: ")
print(locationManager.location.coordinate.latitude)
print(" lon: ")
println(locationManager.location.coordinate.longitude)
}else{
println("Current location not available.")
}
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
println("Editing")
placesObject.alpha = 1
}
func textFieldDidEndEditing(textField: UITextField) {
println("Done Editing")
placesObject.getCoordinates(placesObject.place)
placesObject.alpha = 0
placesObject.suggestions.removeAllObjects()
placesObject.reloadData()
}
//Member Functions
func startMaps() {
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
var cameraZoom: float_t = 5.0
var target: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
if(locationManager.location != nil){
var location: CLLocation = locationManager.location
target = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
cameraZoom = 3
}else{
target = CLLocationCoordinate2D(latitude: 0, longitude: 0)
cameraZoom = 3
}
var camera: GMSCameraPosition = GMSCameraPosition(target: target, zoom: cameraZoom, bearing: 0, viewingAngle: 0)
if let map = mapView? {
map.settings.myLocationButton = true
map.camera = camera
map.delegate = self
loadMarkers()
}
}
func loadMarkers() {
//Remove all markers
for object in markers {
let marker: GMSMarker = object as GMSMarker
marker.map = nil
}
//Add all markers
for object in container.feedData as NSMutableArray{
let point:PFObject = object as PFObject
let location: PFGeoPoint = point.objectForKey("location") as PFGeoPoint
var position: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let marker: GMSMarker = GMSMarker(position: position)
marker.map = mapView
marker.title = point.objectForKey("caption") as String
markers.addObject(marker)
}
}
func addPost(place: Place) {
println(placesObject.place.location)
container.postView.location = placesObject.place.location
presentViewController(container.postView, animated: true, completion: nil)
addressInputField.text = ""
}
func addCurrentLocationIcon(){
if(locationManager.location != nil){
var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: locationManager.location.coordinate.latitude, longitude: locationManager.location.coordinate.longitude)
currentLocationIcon = CurrentLocationIcon(mapView: mapView, location: location)
}else{
println("Current Location not available!")
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: NSArray) -> Void {
var coor: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: locationManager.location.coordinate.latitude, longitude: locationManager.location.coordinate.longitude)
//Sometimes calls on nil
currentLocationIcon.updateLocation(coor)
//when the icon changes location we need to make it animate, not redraw at that location
}
}
|
mit
|
bf00fafcbd4b04457615c836aa431be1
| 35.405263 | 187 | 0.655581 | 5.519553 | false | false | false | false |
yzhou65/DSWeibo
|
DSWeibo/Classes/Home/HomeTableViewController.swift
|
1
|
13161
|
//
// HomeTableViewController.swift
// DSWeibo
//
// Created by Yue on 9/6/16.
// Copyright © 2016 fda. All rights reserved.
//
import UIKit
import SVProgressHUD
let YZHomeReuseIdentifier = "YZHomeReuseIdentifier"
class HomeTableViewController: BaseTableViewController {
///用于保存微博数组
var statuses:[Status]? {
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// SVProgressHUD.showInfoWithStatus("我来了")
//如果没有登录,就要设置未登录界面信息
if !userLogin {
visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,会这里看看有什么惊喜")
return
}
//初始化导航条
setupNav()
//注册通知,监听菜单的弹出与关闭
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(change), name: YZPopoverAnimatorWillShow, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(change), name: YZPopoverAnimatorWillDismiss, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showPhotoBrowser), name: YZStatusPictureViewSelected, object: nil)
//注册2个cell
tableView.registerClass(StatusNormalTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.NormalCell.rawValue)
tableView.registerClass(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.ForwardCell.rawValue)
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//添加自定义的下拉刷新控件
/*
refreshControl = UIRefreshControl()
let refreshView = UIView()
refreshView.backgroundColor = UIColor.redColor()
refreshView.frame = CGRect(x: 0, y: 0, width: 375, height: 60)
refreshControl?.addSubview(refreshView)
*/
refreshControl = HomeRefreshViewControl()
refreshControl?.addTarget(self, action: #selector(loadBlogData), forControlEvents: UIControlEvents.ValueChanged)
newStatusLabel.hidden = false
//加载微博数据
loadBlogData()
}
/**
显示图片浏览器
*/
func showPhotoBrowser(note: NSNotification) {
// print(note.userInfo)
//注意:通过通知传递数据,一定要判断数据是否存在
guard let indexPath = note.userInfo![YZStatusPictureViewIndexKey] as? NSIndexPath else {
print("No indexPath")
return
}
guard let urls = note.userInfo![YZStatusPictureViewURLsKey] as? [NSURL] else {
print("No pictures")
return
}
//创建图片浏览器
let vc = PhotoBrowserController(index: indexPath.item, urls: urls)
//modal图片浏览器
presentViewController(vc, animated: true, completion: nil)
}
deinit {
//移除通知
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/// 定义变量记录当前是上拉还是下拉
var pullupRefreshFlag = false
/**
获取微博数据
如果想调用一个私有方法:
1. 去掉private
2. 加上@objc的前缀,当作OC方法来处理。因为OC可以运行时再寻找方法,OC中没有private的概念
*/
@objc private func loadBlogData() {
//loadStatuses内部发送异步请求,所以为了保证请求结束后再赋值给statuses就要使用闭包,而不是self.statuses = Status.loadStatuses()
/*
默认返回最新20条数据
since_id:会返回比since_id大的微博
max_id:会返回小于等于max_id的微博
每条微博都有一个微博ID,而且微博ID越后面发送的微博,其微博ID越大,递增
新浪返回给我们的微博数据,是从大到小的返回的
*/
/// 默认当做下拉处理
var since_id = statuses?.first?.id ?? 0
var max_id = 0
// 判断是否是上拉
if pullupRefreshFlag {
since_id = 0
max_id = statuses?.last?.id ?? 0
}
Status.loadStatuses(since_id, max_id: max_id) { (models, error) in
//结束刷新动画
self.refreshControl?.endRefreshing()
if error != nil {
return
}
// 下拉刷新
if since_id > 0 {
//如果是下拉刷新,就将获取到的数据,拼接再原有数据前面. Swift中可直接用+来合并两个类型相同的数组
self.statuses = models! + self.statuses!
// 显示刷新提醒
self.showNewStatusCount(models?.count ?? 0)
} else if max_id > 0 {
//如果是上拉加载更多,就将获取到的数据,拼接在原有数据的后面
self.statuses = self.statuses! + models!
}
else {
self.statuses = models
}
}
}
/**
此方法会被两次调用
*/
private func showNewStatusCount(count: Int) {
newStatusLabel.alpha = 1.0
newStatusLabel.text = (count == 0) ? "没有刷新到新微博数据" : "刷新到\(count)条微博数据"
//动画,记录提醒控件的fram
/*
let rect = newStatusLabel.frame
UIView.animateWithDuration(1, animations: {
UIView.setAnimationRepeatAutoreverses(true)
self.newStatusLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
}) { (_) in
self.newStatusLabel.frame = rect
}
*/
//也可以用transform来做
UIView.animateWithDuration(1.5, animations: {
self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height)
}) { (_) in
UIView.animateWithDuration(1.5, animations: {
self.newStatusLabel.transform = CGAffineTransformIdentity
}, completion: { (_) in
self.newStatusLabel.hidden = true
})
}
}
/**
监听菜单的弹出与关闭,修改标题按钮的状态
*/
func change() {
//修改标题按钮的状态
let titleBtn = navigationItem.titleView as! TitleButton
titleBtn.selected = !titleBtn.selected
}
/**
初始化导航条
*/
private func setupNav() {
/*
//左边按钮
let leftBtn = UIButton()
leftBtn.setImage(UIImage(named: "navigationbar_friendattention"), forState: UIControlState.Normal)
leftBtn.setImage(UIImage(named: "navigationbar_friendattention_highlighted"), forState: UIControlState.Highlighted)
leftBtn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
//右边按钮
let rightBtn = UIButton()
rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
rightBtn.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
*/
//封装的设置左右按钮的方法
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(leftItemClick))
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: #selector(rightItemClick))
//初始化标题按钮
let titleBtn = TitleButton()
titleBtn.setTitle("Barney's fortress", forState: UIControlState.Normal)
titleBtn.addTarget(self, action: #selector(titleBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
navigationItem.titleView = titleBtn
}
/**
监听首页导航条中间按钮的点击
*/
func titleBtnClick(btn: TitleButton) {
//修改箭头方向
// btn.selected = !btn.selected //通知方法中改过了,此处不需要再改
//弹出菜单
let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
//设置专场代理和转场
//默认情况下,modal会移除以前控制器的view,替换为当前弹出的view
//如果自定义转场,那么就不会移除以前控制器的view
// vc?.transitioningDelegate = self
//用自己作为转场动画代理不合适,改用一个PopoverAnimator对象来管理
vc?.transitioningDelegate = popoverAnimator
vc?.modalPresentationStyle = UIModalPresentationStyle.Custom //这里用自定义转场样式,而不是Popover,这样就不会移除以前的控制器view,而是直接盖上面modal
presentViewController(vc!, animated: true, completion: nil)
}
func leftItemClick(){
print(#function)
}
/**
监听首页导航条右边的按钮
*/
func rightItemClick(){
// print(#function)
let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
presentViewController(vc!, animated: true
, completion: nil)
}
//MARK: - 懒加载[
/**
一定要定义一个属性来保存自定义转场对象,否则会报错
*/
private lazy var popoverAnimator: PopoverAnimator = {
let pa = PopoverAnimator()
pa.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350)
return pa
}()
/// 刷新提醒控件
private lazy var newStatusLabel: UILabel = {
let label = UILabel()
let height: CGFloat = 44
label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
label.backgroundColor = UIColor.redColor()
label.textAlignment = NSTextAlignment.Center
label.textColor = UIColor.whiteColor()
label.font = UIFont.systemFontOfSize(14)
label.alpha = 0.0
//添加label到界面上
// self.tableView.addSubview(label)
self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
//添加label到界面
return label
}()
/// 微博行高的缓存,利用字典作为容器,key就是微博的id,value是行高
var rowCache: [Int: CGFloat] = [Int: CGFloat]()
/**
如果不停刷微博会导致缓存太多行高。所以当接收到内存警告时,清空rowCache
*/
override func didReceiveMemoryWarning() {
//清空缓存
rowCache.removeAll()
}
}
extension HomeTableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statuses?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let status = statuses![indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusTableViewCell
//设置cell的数据
cell.status = status
//判断是否滚动到了最后一行
let count = statuses?.count ?? 0
if indexPath.row == (count - 1) {
pullupRefreshFlag = true
loadBlogData() //获取更多微博数据
}
return cell
}
/**
返回行高。此方法调用非常频繁
*/
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//取出对应行模型
let status = statuses![indexPath.row]
//判断缓存中有否行高
if let height = rowCache[status.id] {
// print("height from cache")
return height
}
//拿到对应cell
//注意:不要使用tableView.dequeueReusableCellWithIdentifier(identifier: String, forIndexPath: NSIndexPath),会导致方法的循环调用
let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status)) as! StatusTableViewCell
//拿到对应行的行高
let rowHeight = cell.rowHeight(status)
//缓存行高
rowCache[status.id] = rowHeight
// print("recalculate height")
return rowHeight
}
}
|
apache-2.0
|
2f474574f6f6a017e06ef20a583ce1e6
| 31.52 | 159 | 0.605693 | 4.70525 | false | false | false | false |
ChristianKienle/highway
|
Sources/Url/Absolute.swift
|
1
|
3723
|
import Foundation
/// This type ensured two things:
/// 1. It always represents an absolute file url
/// 2. It always works with standardized urls
public struct Absolute {
// MARK: - Globals
public static let root = Absolute("/")
// MARK: - Init
public init(_ absPath: String) {
precondition(absPath.isAbsolutePath)
self.init(URL(fileURLWithPath: absPath))
}
public init(path: String, relativeTo base: Absolute) {
self = base.appending(path)
}
public init(_ fileURL: URL) {
precondition(fileURL.isFileURL)
_url = fileURL.standardizedFileURL
assert(_url.pathComponents.first == "/")
}
// MARK: - Properties
private var _url: URL
public var path: String {
return url.path
}
public var asRelativePath: String {
return String(path.dropFirst())
}
public fileprivate(set) var url: URL {
set {
_url = newValue.standardizedFileURL
}
get {
return _url
}
}
public var urlsFromRootToSelf: (root: Absolute, remainingUrls: [Absolute]) {
var current = self
var urls = [Absolute]()
while current.isRoot == false {
urls.append(current)
current = current.parent
}
let result = Array(urls.reversed())
return (root: .root, remainingUrls: result)
}
}
extension Absolute: Hashable {
public var hashValue: Int {
return url.hashValue
}
}
extension Absolute: Equatable {
public static func ==(lhs: Absolute, rhs: Absolute) -> Bool {
return lhs.url == rhs.url
}
}
extension Absolute : CustomStringConvertible {
public var description: String {
return "\(url.path)"
}
}
extension Absolute : CustomDebugStringConvertible {
public var debugDescription: String {
return "\(url.path)"
}
}
extension Absolute {
public var isRoot: Bool {
return url.pathComponents == ["/"]
}
public var parent: Absolute {
guard isRoot == false else {
return self
}
let parentURL = url.deletingLastPathComponent().standardizedFileURL
return Absolute(parentURL)
}
public var lastPathComponent: String { return url.lastPathComponent }
public func appending(_ subpath: String) -> Absolute {
return Absolute(url.appendingPathComponent(subpath).standardizedFileURL)
}
public func appending(_ relativePath: Relative) -> Absolute {
return appending(relativePath.asString)
}
}
// MARK: - FileManager Support for Absolute, so that we do not have to expose a URL.
public extension FileManager {
public func removeItem(atAbsolute url: Absolute) throws {
try removeItem(at: url.url)
}
public func createDirectory(atAbsolute url: Absolute, withIntermediateDirectories createIntermediates: Bool) throws {
try createDirectory(at: url.url, withIntermediateDirectories: createIntermediates, attributes: nil)
}
}
public extension Data {
public func write(toAbsolute url: Absolute) throws {
try write(to: url.url)
}
public init(contentsOfAbsolute url: Absolute) throws {
try self.init(contentsOf: url.url)
}
}
public extension String {
public var isAbsolutePath: Bool { return hasPrefix("/") }
}
extension Absolute: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
|
mit
|
eae77419977d898fa30c7ab8f68dc058
| 26.375 | 121 | 0.638464 | 4.718631 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.