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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nacker/CarouselView
|
图片轮播Swift/图片轮播Swift/LZPageView.swift
|
1
|
4027
|
//
// LZPageView.swift
// 图片轮播Swift
//
// Created by nacker QQ:648959 on 15/12/15.
// Copyright © 2015年 Shanghai Minlan Information & Technology Co ., Ltd. All rights reserved.
//
import UIKit
protocol LZPageViewDelegate {
func pageView(pageView: LZPageView, didSelectedPageAtIndex index: NSInteger);
}
class LZPageView: UIView {
let pageControllHeight: CGFloat = 20
var scrollView: UIScrollView!
var pageControl: UIPageControl!
var timer: NSTimer!
var statusArray = [String]() {
didSet {
print(statusArray)
let scrollViewWidth = scrollView.frame.size.width
let scrollViewHeight = scrollView.frame.size.height
for (var i = 0; i < statusArray.count; i++){
let button:UIButton = UIButton()
button.tag = i
button.frame = CGRectMake(CGFloat(i) * scrollViewWidth, 0, scrollViewWidth, scrollViewHeight)
button.setImage(UIImage(named:statusArray[i]), forState:.Normal)
button.addTarget(self, action: "btnClick:", forControlEvents: .TouchDown)
button.contentMode = UIViewContentMode.ScaleAspectFill
self.scrollView.addSubview(button)
}
self.scrollView.contentSize = CGSizeMake(scrollViewWidth * CGFloat(statusArray.count), 0)
self.pageControl.numberOfPages = statusArray.count;
}
}
var delegate: LZPageViewDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
setupScrollView()
setupPageControl()
startTimer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupScrollView() {
scrollView = UIScrollView(frame: CGRect(origin: CGPointZero, size: self.frame.size))
scrollView.pagingEnabled = true
scrollView.delegate = self
scrollView.showsHorizontalScrollIndicator = false
self.addSubview(scrollView)
}
func setupPageControl() {
pageControl = UIPageControl(frame: CGRect(x: 0, y: scrollView.frame.size.height - pageControllHeight, width: scrollView.frame.size.width, height: pageControllHeight))
pageControl.currentPage = 0;
pageControl.center = CGPointMake(self.center.x, pageControl.center.y)
pageControl.pageIndicatorTintColor = UIColor.redColor();
pageControl.currentPageIndicatorTintColor = UIColor.blackColor();
self.addSubview(pageControl)
}
}
extension LZPageView {
@objc private func btnClick(button:UIButton) {
print("btnClick---")
if delegate != nil {
delegate.pageView(self, didSelectedPageAtIndex: button.tag)
}
}
}
extension LZPageView: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
self.pageControl.currentPage = Int(scrollView.contentOffset.x / self.scrollView.frame.size.width + 0.5)
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
stopTimer()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startTimer()
}
func startTimer() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "nextPage:", userInfo: nil, repeats: true)
NSRunLoop .mainRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
}
func stopTimer() {
self.timer?.invalidate()
self.timer = nil
}
func nextPage(timer : NSTimer) {
var index = self.pageControl.currentPage + 1
if index == self.statusArray.count {
index = 0
}
let offSet : CGPoint = CGPointMake(self.scrollView.frame.size.width * CGFloat(index), 0)
self.scrollView .setContentOffset(offSet, animated: true)
}
}
|
apache-2.0
|
fdd983926de0f2dac72635f04b8acdb3
| 30.382813 | 174 | 0.633964 | 4.98263 | false | false | false | false |
newlix/swift-syncable-api
|
Tests/helper.swift
|
1
|
2488
|
//
// helper.swift
// api
//
// Created by newlix on 1/22/16.
// Copyright © 2016 newlix. All rights reserved.
//
import Foundation
import UIKit
import SyncableAPI
import RealmSwift
public var merges = [[String: AnyObject]]()
class Fake: Object, Syncable {
dynamic var id: String = ""
dynamic var updateTimestamp: Double = 0
dynamic var createTimestamp: Double = 0
dynamic var deleted: Bool = false
dynamic var _push: Bool = false
dynamic var _pullTimestamp: Double = 0
dynamic var _retry: Int = 0
dynamic var _hidden: String = ""
override static func primaryKey() -> String? {
return "id"
}
static func didMerge(dict: [String: AnyObject]) throws {
merges.append(dict)
}
}
class Parent: Object, Syncable {
dynamic var id: String = ""
dynamic var updateTimestamp: Double = 0
dynamic var createTimestamp: Double = 0
dynamic var deleted: Bool = false
dynamic var _push: Bool = false
dynamic var _pullTimestamp: Double = 0
dynamic var _retry: Int = 0
dynamic var fake: Fake?
dynamic var _hiddenFake: Fake?
override static func primaryKey() -> String? {
return "id"
}
static func didMerge(dict: [String: AnyObject]) throws {
}
}
func clearNSUserDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
let dict = defaults.dictionaryRepresentation()
for (key, _) in dict {
defaults.removeObjectForKey(key)
}
}
func clearRealm() {
let realm = try! Realm()
realm.beginWrite()
realm.deleteAll()
try! realm.commitWrite()
}
func clearBeforeTesting() {
clearNSUserDefaults()
clearRealm()
merges.removeAll()
}
func parseFindOrCountParams(json: AnyObject) -> (query: [String: AnyObject]?, options: [String: AnyObject]?, lastId: String?, lastCommitTimestamp: Double?) {
let params = json as! [String: AnyObject]
return (
params["query"] as? [String: AnyObject],
params["options"] as? [String: AnyObject],
params["lastId"] as? String,
params["lastCommitTimestamp"] as? Double
)
}
// token payload
//{
// "userId": "lessId",
// "roles": [
// "admin"
// ]
//}
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJsZXNzSWQiLCJyb2xlcyI6WyJhZG1pbiJdfQ.6KOyggiYyG_-YkzZi_sXAUfYIJ37mFdSJzACKjQHZOo"
let secret = "secret"
let lessMockServiceURLString = "http://localhost:5000/"
//let lessMockServiceURLString = "http://lessmock.herokuapp.com/"
|
mit
|
1cb4f4f4758e0615bbdee4e1edb5d5fc
| 26.032609 | 157 | 0.66546 | 3.678994 | false | false | false | false |
PetroccoCo/Lock.iOS-OSX
|
Examples/Cognito.Swift/Auth0Cognito/HomeViewController.swift
|
3
|
2702
|
// HomeViewController.swift
//
// Copyright (c) 2014 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
class HomeViewController: UIViewController {
let loginManager = MyApplication.sharedInstance.loginManager
override func viewDidLoad() {
super.viewDidLoad()
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
let success = {() -> () in
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.performSegueWithIdentifier("showProfile", sender: self)
}
let failure = {(error:NSError!) -> () in
MBProgressHUD.hideHUDForView(self.view, animated: true)
return
}
self.loginManager.resumeLogin(success, failure)
}
@IBAction func showSignIn(sender: AnyObject) {
let authController = A0LockViewController()
authController.closable = true
authController.onAuthenticationBlock = {(profile:A0UserProfile!, token:A0Token!) -> () in
let loginManager = MyApplication.sharedInstance.loginManager
let success = {() -> () in
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("showProfile", sender: self)
}
let failure = {(error: NSError!) -> () in
NSLog("Error logging the user in %s", error!.description);
}
self.loginManager.completeLogin(token, profile, success, failure)
}
self.presentViewController(authController, animated: true, completion: nil)
}
}
|
mit
|
fe7355bd5b87e83285a08ea41c7ff9d2
| 39.328358 | 97 | 0.673575 | 4.976059 | false | false | false | false |
fireunit/login
|
Pods/Material/Sources/iOS/BarView.swift
|
2
|
2830
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class BarView : ControlView {
/// Device status bar style.
public var statusBarStyle: UIStatusBarStyle {
get {
return MaterialDevice.statusBarStyle
}
set(value) {
MaterialDevice.statusBarStyle = value
}
}
/// A convenience initializer.
public convenience init() {
self.init(frame: CGRectZero)
}
/**
A convenience initializer with parameter settings.
- Parameter leftControls: An Array of UIControls that go on the left side.
- Parameter rightControls: An Array of UIControls that go on the right side.
*/
public convenience init?(leftControls: Array<UIControl>? = nil, rightControls: Array<UIControl>? = nil) {
self.init(frame: CGRectZero)
prepareProperties(leftControls, rightControls: rightControls)
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public override func prepareView() {
super.prepareView()
depth = .Depth1
spacingPreset = .Spacing1
contentInsetPreset = .Square1
autoresizingMask = .FlexibleWidth
shadowPathAutoSizeEnabled = false
}
}
|
mit
|
6d5dc9dbdefa9d658f72c6cb6ffaf7cb
| 37.243243 | 106 | 0.769965 | 4.274924 | false | false | false | false |
alexburtnik/ABSwiftExtensions
|
ABSwiftExtensions/Classes/UIKit/UIViewContoller.swift
|
1
|
1667
|
//
// UIViewContoller+Extensions.swift
// Pods
//
// Created by Alex Burtnik on 8/31/17.
//
//
import Foundation
import UIKit
public extension UIViewController {
public var isVisible: Bool {
return isViewLoaded && view.window != nil
}
public func showError(message: String?) {
let message = message ?? NSLocalizedString("Unknown error", comment: "Error handling")
let title = NSLocalizedString("Error", comment: "Error handling")
showMessage(title: title, message: message)
}
public func showMessage(title: String?, message: String?) {
guard isVisible else { return }
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = NSLocalizedString("Ok", comment: "Alert button")
alert.addAction(UIAlertAction(title: ok, style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
public func showDialog(title: String?,
message: String?,
actionTitle: String? = NSLocalizedString("Ok", comment: "Alert button"),
cancelTitle: String? = NSLocalizedString("Cancel", comment: "Alert button"),
action: @escaping ()->Void) {
guard isVisible else { return }
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { _ in action() }))
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
|
mit
|
136809b36039ff9b057f8f2cb766a5f0
| 37.767442 | 103 | 0.637672 | 4.682584 | false | false | false | false |
envoy/Embassy
|
Sources/SystemLibrary.swift
|
1
|
8916
|
//
// SystemLibrary.swift
// Embassy
//
// Created by Fang-Pen Lin on 1/14/17.
// Copyright © 2017 Fang-Pen Lin. All rights reserved.
//
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// Collection of system library methods and constants
struct SystemLibrary {
#if os(Linux)
// MARK: Linux constants
static let fdSetSize = FD_SETSIZE
static let nfdbits: Int32 = Int32(MemoryLayout<Int>.size) * 8
// MARK: Linux methods
static let pipe = Glibc.pipe
static let socket = Glibc.socket
static let select = Glibc.select
static let htons = Glibc.htons
static let ntohs = Glibc.ntohs
static let connect = Glibc.connect
static let bind = Glibc.bind
static let listen = Glibc.listen
static let accept = Glibc.accept
static let send = Glibc.send
static let recv = Glibc.recv
static let read = Glibc.read
static let shutdown = Glibc.shutdown
static let close = Glibc.close
static let getpeername = Glibc.getpeername
static let getsockname = Glibc.getsockname
static func fdSet(fd: Int32, set: inout fd_set) {
let intOffset = Int(fd / SystemLibrary.nfdbits)
let bitOffset = Int(fd % SystemLibrary.nfdbits)
let mask = 1 << bitOffset
switch intOffset {
case 0: set.__fds_bits.0 = set.__fds_bits.0 | mask
case 1: set.__fds_bits.1 = set.__fds_bits.1 | mask
case 2: set.__fds_bits.2 = set.__fds_bits.2 | mask
case 3: set.__fds_bits.3 = set.__fds_bits.3 | mask
case 4: set.__fds_bits.4 = set.__fds_bits.4 | mask
case 5: set.__fds_bits.5 = set.__fds_bits.5 | mask
case 6: set.__fds_bits.6 = set.__fds_bits.6 | mask
case 7: set.__fds_bits.7 = set.__fds_bits.7 | mask
case 8: set.__fds_bits.8 = set.__fds_bits.8 | mask
case 9: set.__fds_bits.9 = set.__fds_bits.9 | mask
case 10: set.__fds_bits.10 = set.__fds_bits.10 | mask
case 11: set.__fds_bits.11 = set.__fds_bits.11 | mask
case 12: set.__fds_bits.12 = set.__fds_bits.12 | mask
case 13: set.__fds_bits.13 = set.__fds_bits.13 | mask
case 14: set.__fds_bits.14 = set.__fds_bits.14 | mask
case 15: set.__fds_bits.15 = set.__fds_bits.15 | mask
default: break
}
}
static func fdIsSet(fd: Int32, set: inout fd_set) -> Bool {
let intOffset = Int(fd / SystemLibrary.nfdbits)
let bitOffset = Int(fd % SystemLibrary.nfdbits)
let mask = Int(1 << bitOffset)
switch intOffset {
case 0: return set.__fds_bits.0 & mask != 0
case 1: return set.__fds_bits.1 & mask != 0
case 2: return set.__fds_bits.2 & mask != 0
case 3: return set.__fds_bits.3 & mask != 0
case 4: return set.__fds_bits.4 & mask != 0
case 5: return set.__fds_bits.5 & mask != 0
case 6: return set.__fds_bits.6 & mask != 0
case 7: return set.__fds_bits.7 & mask != 0
case 8: return set.__fds_bits.8 & mask != 0
case 9: return set.__fds_bits.9 & mask != 0
case 10: return set.__fds_bits.10 & mask != 0
case 11: return set.__fds_bits.11 & mask != 0
case 12: return set.__fds_bits.12 & mask != 0
case 13: return set.__fds_bits.13 & mask != 0
case 14: return set.__fds_bits.14 & mask != 0
case 15: return set.__fds_bits.15 & mask != 0
default: return false
}
}
#else
// MARK: Darwin constants
static let fdSetSize = __DARWIN_FD_SETSIZE
// MARK: Darwin methods
static let pipe = Darwin.pipe
static let socket = Darwin.socket
static let select = Darwin.select
static let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
static let htons = isLittleEndian ? _OSSwapInt16 : { $0 }
static let ntohs = isLittleEndian ? _OSSwapInt16 : { $0 }
static let connect = Darwin.connect
static let bind = Darwin.bind
static let listen = Darwin.listen
static let accept = Darwin.accept
static let send = Darwin.send
static let recv = Darwin.recv
static let read = Darwin.read
static let shutdown = Darwin.shutdown
static let close = Darwin.close
static let getpeername = Darwin.getpeername
static let getsockname = Darwin.getsockname
static func fdSet(fd: Int32, set: inout fd_set) {
let intOffset = Int(fd / 32)
let bitOffset = fd % 32
let mask = Int32(1 << bitOffset)
switch intOffset {
case 0: set.fds_bits.0 = set.fds_bits.0 | mask
case 1: set.fds_bits.1 = set.fds_bits.1 | mask
case 2: set.fds_bits.2 = set.fds_bits.2 | mask
case 3: set.fds_bits.3 = set.fds_bits.3 | mask
case 4: set.fds_bits.4 = set.fds_bits.4 | mask
case 5: set.fds_bits.5 = set.fds_bits.5 | mask
case 6: set.fds_bits.6 = set.fds_bits.6 | mask
case 7: set.fds_bits.7 = set.fds_bits.7 | mask
case 8: set.fds_bits.8 = set.fds_bits.8 | mask
case 9: set.fds_bits.9 = set.fds_bits.9 | mask
case 10: set.fds_bits.10 = set.fds_bits.10 | mask
case 11: set.fds_bits.11 = set.fds_bits.11 | mask
case 12: set.fds_bits.12 = set.fds_bits.12 | mask
case 13: set.fds_bits.13 = set.fds_bits.13 | mask
case 14: set.fds_bits.14 = set.fds_bits.14 | mask
case 15: set.fds_bits.15 = set.fds_bits.15 | mask
case 16: set.fds_bits.16 = set.fds_bits.16 | mask
case 17: set.fds_bits.17 = set.fds_bits.17 | mask
case 18: set.fds_bits.18 = set.fds_bits.18 | mask
case 19: set.fds_bits.19 = set.fds_bits.19 | mask
case 20: set.fds_bits.20 = set.fds_bits.20 | mask
case 21: set.fds_bits.21 = set.fds_bits.21 | mask
case 22: set.fds_bits.22 = set.fds_bits.22 | mask
case 23: set.fds_bits.23 = set.fds_bits.23 | mask
case 24: set.fds_bits.24 = set.fds_bits.24 | mask
case 25: set.fds_bits.25 = set.fds_bits.25 | mask
case 26: set.fds_bits.26 = set.fds_bits.26 | mask
case 27: set.fds_bits.27 = set.fds_bits.27 | mask
case 28: set.fds_bits.28 = set.fds_bits.28 | mask
case 29: set.fds_bits.29 = set.fds_bits.29 | mask
case 30: set.fds_bits.30 = set.fds_bits.30 | mask
case 31: set.fds_bits.31 = set.fds_bits.31 | mask
default: break
}
}
static func fdIsSet(fd: Int32, set: inout fd_set) -> Bool {
let intOffset = Int(fd / 32)
let bitOffset = fd % 32
let mask = Int32(1 << bitOffset)
switch intOffset {
case 0: return set.fds_bits.0 & mask != 0
case 1: return set.fds_bits.1 & mask != 0
case 2: return set.fds_bits.2 & mask != 0
case 3: return set.fds_bits.3 & mask != 0
case 4: return set.fds_bits.4 & mask != 0
case 5: return set.fds_bits.5 & mask != 0
case 6: return set.fds_bits.6 & mask != 0
case 7: return set.fds_bits.7 & mask != 0
case 8: return set.fds_bits.8 & mask != 0
case 9: return set.fds_bits.9 & mask != 0
case 10: return set.fds_bits.10 & mask != 0
case 11: return set.fds_bits.11 & mask != 0
case 12: return set.fds_bits.12 & mask != 0
case 13: return set.fds_bits.13 & mask != 0
case 14: return set.fds_bits.14 & mask != 0
case 15: return set.fds_bits.15 & mask != 0
case 16: return set.fds_bits.16 & mask != 0
case 17: return set.fds_bits.17 & mask != 0
case 18: return set.fds_bits.18 & mask != 0
case 19: return set.fds_bits.19 & mask != 0
case 20: return set.fds_bits.20 & mask != 0
case 21: return set.fds_bits.21 & mask != 0
case 22: return set.fds_bits.22 & mask != 0
case 23: return set.fds_bits.23 & mask != 0
case 24: return set.fds_bits.24 & mask != 0
case 25: return set.fds_bits.25 & mask != 0
case 26: return set.fds_bits.26 & mask != 0
case 27: return set.fds_bits.27 & mask != 0
case 28: return set.fds_bits.28 & mask != 0
case 29: return set.fds_bits.29 & mask != 0
case 30: return set.fds_bits.30 & mask != 0
case 31: return set.fds_bits.31 & mask != 0
default: return false
}
}
#endif
}
|
mit
|
bbc96a31d6f1c59e2baa1aa54ecae917
| 44.253807 | 76 | 0.54212 | 3.507081 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/Modal Resonance Filter/AKModalResonanceFilter.swift
|
1
|
4801
|
//
// AKModalResonanceFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// A modal resonance filter used for modal synthesis. Plucked and bell sounds
/// can be created using passing an impulse through a combination of modal
/// filters.
///
/// - Parameters:
/// - input: Input node to process
/// - frequency: Resonant frequency of the filter.
/// - qualityFactor: Quality factor of the filter. Roughly equal to Q/frequency.
///
public class AKModalResonanceFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKModalResonanceFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var qualityFactorParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Resonant frequency of the filter.
public var frequency: Double = 500.0 {
willSet {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Quality factor of the filter. Roughly equal to Q/frequency.
public var qualityFactor: Double = 50.0 {
willSet {
if qualityFactor != newValue {
if internalAU!.isSetUp() {
qualityFactorParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.qualityFactor = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - frequency: Resonant frequency of the filter.
/// - qualityFactor: Quality factor of the filter. Roughly equal to Q/frequency.
///
public init(
_ input: AKNode,
frequency: Double = 500.0,
qualityFactor: Double = 50.0) {
self.frequency = frequency
self.qualityFactor = qualityFactor
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x6d6f6466 /*'modf'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKModalResonanceFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKModalResonanceFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKModalResonanceFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
qualityFactorParameter = tree.valueForKey("qualityFactor") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.qualityFactorParameter!.address {
self.qualityFactor = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.qualityFactor = Float(qualityFactor)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
mit
|
dcb33390ee4feee08e20ba403cd80710
| 32.110345 | 95 | 0.614039 | 5.270033 | false | false | false | false |
benlangmuir/swift
|
benchmark/single-source/DictTest3.swift
|
10
|
2454
|
//===--- DictTest3.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks = [
BenchmarkInfo(name: "Dictionary3", runFunction: run_Dictionary3, tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "Dictionary3OfObjects", runFunction: run_Dictionary3OfObjects, tags: [.validation, .api, .Dictionary]),
]
@inline(never)
public func run_Dictionary3(_ n: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 = [String: Int]()
var hash2 = [String: Int]()
var res = ""
for _ in 1...n {
hash1 = [:]
for i in 0..<size1 {
hash1["foo_" + String(i)] = i
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = hash2[k]! + v
}
}
res = (String(hash1["foo_1"]!) + " " + String(hash1["foo_99"]!) + " " +
String(hash2["foo_1"]!) + " " + String(hash2["foo_99"]!))
if res != ref_result {
break
}
}
check(res == ref_result)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_Dictionary3OfObjects(_ n: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 : [ Box<String> : Box<Int> ] = [:]
var hash2 : [ Box<String> : Box<Int> ] = [:]
var res = ""
for _ in 1...n {
hash1 = [:]
for i in 0..<size1 {
hash1[Box("foo_" + String(i))] = Box(i)
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = Box(hash2[k]!.value + v.value)
}
}
res = (String(hash1[Box("foo_1")]!.value) + " " + String(hash1[Box("foo_99")]!.value) + " " +
String(hash2[Box("foo_1")]!.value) + " " + String(hash2[Box("foo_99")]!.value))
if res != ref_result {
break
}
}
check(res == ref_result)
}
|
apache-2.0
|
cce90a6d229f44751257682ac69728c0
| 24.040816 | 125 | 0.537082 | 3.276368 | false | false | false | false |
LYM-mg/MGDYZB
|
MGDYZB简单封装版/MGDYZB/Class/Tools/Category/UINavigationBar+Extension.swift
|
1
|
5714
|
//
// UINavigationBar+Extension.swift
// MGDYZB
//
// Created by newunion on 2017/12/26.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
// MARK: - ⚠️方法一
extension UINavigationBar {
// MARK: - RunTime
private struct NavigationBarKeys {
static var overlayKey = "overlayKey"
}
var overlay: UIView? {
get {
return objc_getAssociatedObject(self, &NavigationBarKeys.overlayKey) as? UIView
}
set {
objc_setAssociatedObject(self, &NavigationBarKeys.overlayKey, newValue as UIView?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
// MARK: - 接口
func Mg_setBackgroundColor(backgroundColor: UIColor) {
if overlay == nil {
self.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
overlay = UIView.init(frame: CGRect.init(x: 0, y: 0, width: bounds.width, height: bounds.height+20))
overlay?.isUserInteractionEnabled = false
overlay?.autoresizingMask = UIView.AutoresizingMask.flexibleWidth
}
overlay?.backgroundColor = backgroundColor
subviews.first?.insertSubview(overlay!, at: 0)
}
func Mg_setTranslationY(translationY: CGFloat) {
transform = CGAffineTransform.init(translationX: 0, y: translationY)
}
func Mg_setElementsAlpha(alpha: CGFloat) {
for (_, element) in subviews.enumerated() {
if element.isKind(of: NSClassFromString("UINavigationItemView") as! UIView.Type) ||
element.isKind(of: NSClassFromString("UINavigationButton") as! UIButton.Type) ||
element.isKind(of: NSClassFromString("UINavBarPrompt") as! UIView.Type)
{
element.alpha = alpha
}
if element.isKind(of: NSClassFromString("_UINavigationBarBackIndicatorView") as! UIView.Type) {
element.alpha = element.alpha == 0 ? 0 : alpha
}
}
items?.forEach({ (item) in
if let titleView = item.titleView {
titleView.alpha = alpha
}
for BBItems in [item.leftBarButtonItems, item.rightBarButtonItems] {
BBItems?.forEach({ (barButtonItem) in
if let customView = barButtonItem.customView {
customView.alpha = alpha
}
})
}
})
}
/// viewWillDisAppear调用
func Mg_reset() {
setBackgroundImage(nil, for: UIBarMetrics.default)
overlay?.removeFromSuperview()
overlay = nil
}
}
// MARK: -
// MARK: -
// MARK: - ⚠️方法二
extension UINavigationBar {
// MARK: - 接口
/**
* 隐藏导航栏下的横线,背景色置空 viewWillAppear调用
*/
func star() {
let shadowImg: UIImageView? = self.findNavLineImageViewOn(view: self)
shadowImg?.isHidden = true
self.backgroundColor = nil
}
/**
在func scrollViewDidScroll(_ scrollView: UIScrollView)调用
@param color 最终显示颜色
@param scrollView 当前滑动视图
@param value 滑动临界值,依据需求设置
*/
func change(_ color: UIColor, with scrollView: UIScrollView, andValue value: CGFloat,colorIsStartExit: Bool=false) {
if scrollView.contentOffset.y < -value{
//下拉时导航栏隐藏
self.isHidden = true
} else {
self.isHidden = false
//计算透明度
var alpha: CGFloat = scrollView.contentOffset.y / value > 1.0 ? 1 : scrollView.contentOffset.y / value
alpha = colorIsStartExit ? (1 - alpha) : alpha
//设置一个颜色并转化为图片
let image: UIImage? = imageFromColor(color: color.withAlphaComponent(alpha))
self.setBackgroundImage(image, for: .default)
if (colorIsStartExit) {
self.isHidden = alpha == 0
}
print(alpha)
}
}
/**
* 还原导航栏 viewWillDisAppear调用
*/
func reset() {
let shadowImg = findNavLineImageViewOn(view: self)
shadowImg?.isHidden = false
self.setBackgroundImage(nil,for: .default)
}
// MARK: - 其他内部方法
//寻找导航栏下的横线 递归查询
fileprivate func findNavLineImageViewOn(view: UIView) -> UIImageView? {
if (view.isKind(of: UIImageView.classForCoder()) && view.bounds.size.height <= 1.0) {
return view as? UIImageView
}
for subView in view.subviews {
let imageView = findNavLineImageViewOn(view: subView)
if imageView != nil {
return imageView
}
}
return nil
}
// Color To Image
fileprivate func imageFromColor(color: UIColor) -> UIImage {
//创建1像素区域并开始图片绘图
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
//创建画板并填充颜色和区域
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
//从画板上获取图片并关闭图片绘图
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
// MARK: - 单独隐藏导航栏下划线
func hideNavgationBottomLine(_ isHidden: Bool) {
self.findNavLineImageViewOn(view: self)?.isHidden = (isHidden ? true : false)
}
}
|
mit
|
b4fa50fc52e72a655c1b680497f8f200
| 30.7 | 151 | 0.58304 | 4.570823 | false | false | false | false |
tnantoka/edhita
|
Edhita/Views/AdBannerView.swift
|
1
|
1866
|
//
// AdBannerView.swift
// Edhita
//
// Created by Tatsuya Tobioka on 2022/08/04.
//
import GoogleMobileAds
import SwiftUI
struct AdBannerView: View {
var body: some View {
#if DEBUG
let height = Constants.enableAd ? [50, 100].randomElement() ?? 50 : 0
#else
let height = [50, 100].randomElement() ?? 50
#endif
AdBannerViewWithController(height: height).frame(height: CGFloat(height))
}
}
struct AdBannerViewWithController: UIViewControllerRepresentable {
let height: Int
func makeUIViewController(
context: UIViewControllerRepresentableContext<AdBannerViewWithController>
) -> UIViewController {
let controller = UIViewController()
let view = GADBannerView(adSize: height == 50 ? GADAdSizeBanner : GADAdSizeLargeBanner)
#if DEBUG
view.adUnitID = "ca-app-pub-3940256099942544/2934735716"
#else
view.adUnitID = Constants.adUnitID
#endif
view.rootViewController = controller
#if DEBUG
if Constants.enableAd {
view.load(GADRequest())
}
#else
view.load(GADRequest())
#endif
controller.view.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let views = [
"view": view
]
let horizontal = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-|",
options: [],
metrics: nil,
views: views
)
NSLayoutConstraint.activate(horizontal)
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
}
struct AdBannerView_Previews: PreviewProvider {
static var previews: some View {
AdBannerView()
}
}
|
mit
|
0e19f7fd49236ffdbfe7e88e26306b52
| 24.916667 | 95 | 0.61254 | 4.936508 | false | false | false | false |
exshin/PokePuzzler
|
PokePuzzler/GameScene.swift
|
1
|
16305
|
//
// GameScene.swift
// PokePuzzler
//
// Created by Eugene Chinveeraphan on 13/04/16.
// Copyright © 2016 Eugene Chinveeraphan. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
// MARK: Properties
// This is marked as ! because it will not initially have a value, but pretty
// soon after the GameScene is created it will be given a Level object, and
// from then on it will always have one (it will never be nil again).
var level: Level!
let TileWidth: CGFloat = 41.0
let TileHeight: CGFloat = 41.5
let gameLayer = SKNode()
let cookiesLayer = SKNode()
let pokemonLayer = SKNode()
let tilesLayer = SKNode()
let cropLayer = SKCropNode()
let maskLayer = SKNode()
// The column and row numbers of the cookie that the player first touched
// when he started his swipe movement. These are marked ? because they may
// become nil (meaning no swipe is in progress).
var swipeFromColumn: Int?
var swipeFromRow: Int?
// The scene handles touches. If it recognizes that the user makes a swipe,
// it will call this swipe handler. This is how it communicates back to the
// ViewController that a swap needs to take place. You could also use a
// delegate for this.
var swipeHandler: ((Swap) -> ())?
// Sprite that is drawn on top of the cookie that the player is trying to swap.
var selectionSprite = SKSpriteNode()
var scoreLabel: SKLabelNode!
// Pre-load sounds
let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false)
let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false)
let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false)
let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false)
let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false)
// MARK: Init
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder) is not used in this app")
}
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
// Put an image on the background. Because the scene's anchorPoint is
// (0.5, 0.5), the background image will always be centered on the screen.
let background = SKSpriteNode(imageNamed: "Background3")
background.size = size
addChild(background)
// Add a new node that is the container for all other layers on the playing
// field. This gameLayer is also centered in the screen.
gameLayer.isHidden = true
addChild(gameLayer)
let layerPosition = CGPoint(x: -165, y: -310)
// // The tiles layer represents the shape of the level. It contains a sprite
// // node for each square that is filled in.
// tilesLayer.position = layerPosition
// gameLayer.addChild(tilesLayer)
//
// // We use a crop layer to prevent cookies from being drawn across gaps
// // in the level design.
// gameLayer.addChild(cropLayer)
//
// // The mask layer determines which part of the cookiesLayer is visible.
// maskLayer.position = layerPosition
// cropLayer.maskNode = maskLayer
// This layer holds the Cookie sprites. The positions of these sprites
// are relative to the cookiesLayer's bottom-left corner.
cookiesLayer.position = layerPosition
gameLayer.addChild(cookiesLayer)
// This layer holds the Pokemon sprites.
pokemonLayer.position = layerPosition
gameLayer.addChild(pokemonLayer)
// nil means that these properties have invalid values.
swipeFromColumn = nil
swipeFromRow = nil
// Pre-load the label font so prevent delays during game play.
let _ = SKLabelNode(fontNamed: "GillSans-BoldItalic")
}
// MARK: Level Setup
func addTiles() {
for row in 0..<NumRows {
for column in 0..<NumColumns {
// If there is a tile at this position, then create a new tile
// sprite and add it to the mask layer.
if level.tileAt(column: column, row: row) != nil {
let tileNode = SKSpriteNode(imageNamed: "MaskTile")
tileNode.size = CGSize(width: TileWidth, height: TileHeight)
tileNode.position = pointFor(column: column, row: row)
maskLayer.addChild(tileNode)
}
}
}
// The tile pattern is drawn *in between* the level tiles. That's why
// there is an extra column and row of them.
for row in 0...NumRows {
for column in 0...NumColumns {
let topLeft = (column > 0) && (row < NumRows)
&& level.tileAt(column: column - 1, row: row) != nil
let bottomLeft = (column > 0) && (row > 0)
&& level.tileAt(column: column - 1, row: row - 1) != nil
let topRight = (column < NumColumns) && (row < NumRows)
&& level.tileAt(column: column, row: row) != nil
let bottomRight = (column < NumColumns) && (row > 0)
&& level.tileAt(column: column, row: row - 1) != nil
// The tiles are named from 0 to 15, according to the bitmask that is
// made by combining these four values.
let value =
Int(topLeft.hashValue) |
Int(topRight.hashValue) << 1 |
Int(bottomLeft.hashValue) << 2 |
Int(bottomRight.hashValue) << 3
// Values 0 (no tiles), 6 and 9 (two opposite tiles) are not drawn.
if value != 0 && value != 6 && value != 9 {
let name = String(format: "Tile_%ld", value)
let tileNode = SKSpriteNode(imageNamed: name)
tileNode.size = CGSize(width: TileWidth, height: TileHeight)
var point = pointFor(column: column, row: row)
point.x -= TileWidth/2
point.y -= TileHeight/2
tileNode.position = point
tilesLayer.addChild(tileNode)
}
}
}
}
func addSprites(for cookies: Set<Cookie>, completion: @escaping () -> ()) {
for cookie in cookies {
// Create a new sprite for the cookie and add it to the cookiesLayer.
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.size = CGSize(width: TileWidth, height: TileHeight)
sprite.position = pointFor(column: cookie.column, row: cookie.row)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
// Give each cookie sprite a small, random delay. Then fade them in.
sprite.alpha = 0
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.run(
SKAction.sequence([
SKAction.wait(forDuration: 0.1, withRange: 0.2),
SKAction.group([
SKAction.fadeIn(withDuration: 0.1),
SKAction.scale(to: 1.0, duration: 0.1)
])
]))
}
cookiesLayer.run(SKAction.wait(forDuration: 0.2), completion: completion)
}
func removeAllCookieSprites() {
cookiesLayer.removeAllChildren()
}
// Sprites Logic for Pokemon
func addPokemonSprites(for pokemons: Set<Pokemon>) {
for pokemon in pokemons {
// Create a new sprite for the cookie and add it to the cookiesLayer.
let sprite = SKSpriteNode(imageNamed: pokemon.filename)
// TODO - calculate the pokemon locations
if pokemon.PokemonPosition.description == "myPokemon" {
sprite.size = CGSize(width: pokemon.spriteSize + 10, height: pokemon.spriteSize + 10)
sprite.position = CGPoint(x: 82, y: 480)
} else {
sprite.size = CGSize(width: pokemon.spriteSize, height: pokemon.spriteSize)
sprite.position = CGPoint(x: 253, y: 568)
}
pokemonLayer.addChild(sprite)
pokemon.sprite = sprite
// Give each cookie sprite a small, random delay. Then fade them in.
sprite.alpha = 0
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.run(
SKAction.sequence([
SKAction.group([
SKAction.fadeIn(withDuration: 0.1),
SKAction.scale(to: 1.0, duration: 0.1)
])
]))
}
}
// Load Pokemon Info Screens for My Pokemon and Opponent Pokemon
func addPokemonInfo(for pokemons: Set<Pokemon>) {
// Load Info Sprites
let myInfoSprite = SKSpriteNode(imageNamed: "MyInfo")
let opponentInfoSprite = SKSpriteNode(imageNamed: "OpponentInfo")
myInfoSprite.position = CGPoint(x: 223, y: 490)
opponentInfoSprite.position = CGPoint(x: 132, y: 600)
pokemonLayer.addChild(myInfoSprite)
pokemonLayer.addChild(opponentInfoSprite)
// Load HP Bars
for pokemon in pokemons {
let HealthBar = SKSpriteNode(color:SKColor .green, size: CGSize(width: 102, height: 5))
HealthBar.name = pokemon.PokemonPosition.description
HealthBar.anchorPoint = CGPoint(x: 0.0, y: 0.0)
if pokemon.PokemonPosition.description == "myPokemon" {
HealthBar.position = CGPoint(x: 201, y: 479)
} else {
HealthBar.position = CGPoint(x: 98, y: 589)
}
HealthBar.zPosition = 5
pokemonLayer.addChild(HealthBar)
}
}
// Load Moveset and Cost Bars
func addPokemonMoveset(pokemon: Pokemon, view: UIView) {
let moveset = pokemon.moveset
var skillNumber = 0
for skill in moveset {
let xValue = 70 + (skillNumber * 100)
let skillType = skill["type"]! as! String
let skillName = skill["name"]! as! String
// Load Skill Type Sprite (Element)
let skillTypeSprite = SKSpriteNode(imageNamed: skillType)
skillTypeSprite.position = CGPoint(x: xValue - 16, y: 363)
skillTypeSprite.size = CGSize(width: 17, height: 17)
pokemonLayer.addChild(skillTypeSprite)
// Maximum cost bar
let costBackBar = SKSpriteNode(color:SKColor .white, size: CGSize(width: 70, height: 10))
costBackBar.anchorPoint = CGPoint(x: 0.0, y: 0.0)
costBackBar.position = CGPoint(x: xValue - 5, y: 358)
costBackBar.zPosition = 2
pokemonLayer.addChild(costBackBar)
// Current energy cost bar
let costBar = SKSpriteNode(color:SKColor .white, size: CGSize(width: 0, height: 10))
let hexString = self.elementHexString(element: skill["type"]! as! String)
let color = UIColor(hexString: hexString)
costBar.color = color!
costBar.anchorPoint = CGPoint(x: 0.0, y: 0.0)
costBar.position = CGPoint(x: xValue - 5, y: 358)
costBar.zPosition = 3
costBar.name = skillName + "CostBar"
pokemonLayer.addChild(costBar)
skillNumber += 1
}
}
// MARK: Point conversion
// Converts a column,row pair into a CGPoint that is relative to the cookieLayer.
func pointFor(column: Int, row: Int) -> CGPoint {
return CGPoint(
x: CGFloat(column)*TileWidth + TileWidth/2,
y: CGFloat(row)*TileHeight + TileHeight/2)
}
// Converts a point relative to the cookieLayer into column and row numbers.
func convertPoint(_ point: CGPoint) -> (success: Bool, column: Int, row: Int) {
// Is this a valid location within the cookies layer? If yes,
// calculate the corresponding row and column numbers.
if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth &&
point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight {
return (true, Int(point.x / TileWidth), Int(point.y / TileHeight))
} else {
return (false, 0, 0) // invalid location
}
}
// MARK: Cookie Swapping
// We get here after the user performs a swipe. This sets in motion a whole
// chain of events: 1) swap the cookies, 2) remove the matching lines, 3)
// drop new cookies into the screen, 4) check if they create new matches,
// and so on.
func trySwap(horizontal horzDelta: Int, vertical vertDelta: Int) {
let toColumn = swipeFromColumn! + horzDelta
let toRow = swipeFromRow! + vertDelta
// Going outside the bounds of the array? This happens when the user swipes
// over the edge of the grid. We should ignore such swipes.
guard toColumn >= 0 && toColumn < NumColumns else { return }
guard toRow >= 0 && toRow < NumRows else { return }
// Can't swap if there is no cookie to swap with. This happens when the user
// swipes into a gap where there is no tile.
if let toCookie = level.cookieAt(column: toColumn, row: toRow),
let fromCookie = level.cookieAt(column: swipeFromColumn!, row: swipeFromRow!),
let handler = swipeHandler {
// Communicate this swap request back to the ViewController.
let swap = Swap(cookieA: fromCookie, cookieB: toCookie)
handler(swap)
}
}
func showSelectionIndicator(for cookie: Cookie) {
if selectionSprite.parent != nil {
selectionSprite.removeFromParent()
}
if let sprite = cookie.sprite {
let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName)
selectionSprite.size = CGSize(width: TileWidth, height: TileHeight)
selectionSprite.run(SKAction.setTexture(texture))
sprite.addChild(selectionSprite)
selectionSprite.alpha = 1.0
}
}
func hideSelectionIndicator() {
selectionSprite.run(SKAction.sequence([
SKAction.fadeOut(withDuration: 0.3),
SKAction.removeFromParent()]))
}
// MARK: Cookie Swipe Handlers
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
// Convert the touch location to a point relative to the cookiesLayer.
let location = touch.location(in: cookiesLayer)
// Print coordinates of touch
NSLog("X location: %f", location.x)
NSLog("Y Location: %f", location.y)
// If the touch is inside a square, then this might be the start of a
// swipe motion.
let (success, column, row) = convertPoint(location)
if success {
// The touch must be on a cookie, not on an empty tile.
if let cookie = level.cookieAt(column: column, row: row) {
// Remember in which column and row the swipe started, so we can compare
// them later to find the direction of the swipe. This is also the first
// cookie that will be swapped.
swipeFromColumn = column
swipeFromRow = row
showSelectionIndicator(for: cookie)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// If swipeFromColumn is nil then either the swipe began outside
// the valid area or the game has already swapped the cookies and we need
// to ignore the rest of the motion.
guard swipeFromColumn != nil else { return }
guard let touch = touches.first else { return }
let location = touch.location(in: cookiesLayer)
let (success, column, row) = convertPoint(location)
if success {
// Figure out in which direction the player swiped. Diagonal swipes
// are not allowed.
var horzDelta = 0, vertDelta = 0
if column < swipeFromColumn! { // swipe left
horzDelta = -1
} else if column > swipeFromColumn! { // swipe right
horzDelta = 1
} else if row < swipeFromRow! { // swipe down
vertDelta = -1
} else if row > swipeFromRow! { // swipe up
vertDelta = 1
}
// Only try swapping when the user swiped into a new square.
if horzDelta != 0 || vertDelta != 0 {
trySwap(horizontal: horzDelta, vertical: vertDelta)
hideSelectionIndicator()
// Ignore the rest of this swipe motion from now on.
swipeFromColumn = nil
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Remove the selection indicator with a fade-out. We only need to do this
// when the player didn't actually swipe.
if selectionSprite.parent != nil && swipeFromColumn != nil {
hideSelectionIndicator()
}
// If the gesture ended, regardless of whether if was a valid swipe or not,
// reset the starting column and row numbers.
swipeFromColumn = nil
swipeFromRow = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesEnded(touches, with: event)
}
}
|
apache-2.0
|
1078a615f4f1a5147c4e41195ac08455
| 35.231111 | 95 | 0.644198 | 4.283762 | false | false | false | false |
jTanG0506/ProTec100
|
ProTec100/ProTec100/NotificationTableCell.swift
|
1
|
2324
|
//
// NotificationTableCell.swift
// ProTec100
//
// Created by Jonathan Tang on 28/10/2017.
// Copyright © 2017 tang27. All rights reserved.
//
import UIKit
/// Cell for a single notification.
class NotificationTableCell: UITableViewCell {
var cellNotification: AlertNotification
init(notification: AlertNotification) {
self.cellNotification = notification
super.init(style: .default, reuseIdentifier: "cellNotification")
// Setup the cell
// Find out which icon to use
var iconName = "icons8-"
switch cellNotification.type {
case .doorOpen: iconName += "exit"
case .doorClose: iconName += "enter"
case .sms: iconName += "sms"
case .radio: iconName += "radio_tower"
}
// Add the icon to the cell
let iconImage = UIImageView(frame: CGRect(x: 10, y: 10, width: viewWidth / 15 - 20, height: viewWidth / 15 - 20))
iconImage.image = UIImage(named: iconName)
contentView.addSubview(iconImage)
// Add the content title to the cell
let cellTitle = UILabel(frame: CGRect(x: viewWidth / 15, y: 10, width: 4 * viewWidth / 15 - 10, height: viewWidth / 24 - 15))
switch cellNotification.type {
case .doorOpen: cellTitle.text = "Door Sensor - Opened"
case .doorClose: cellTitle.text = "Door Sensor - Closed"
case .sms: cellTitle.text = "SMS Message"
case .radio: cellTitle.text = "Radio Call"
}
cellTitle.font = UIFont(name: "SourceSansPro-Semibold", size: 17.0)
contentView.addSubview(cellTitle)
// Add the content message to the cell
let cellMessage = UILabel(frame: CGRect(x: viewWidth / 15, y: viewWidth / 24 - 10, width: 4 * viewWidth / 15 - 10, height: viewWidth / 24 - 15))
cellMessage.text = cellNotification.content
cellMessage.font = UIFont(name: "SourceSansPro-Regular", size: 17.0)
contentView.addSubview(cellMessage)
// Add the timestamp of the message
let cellTime = UILabel(frame: CGRect(x: 4 * viewWidth / 15 + 10, y: viewWidth / 24 - 25, width: viewWidth / 15 - 10, height: viewWidth / 24 - 15))
cellTime.text = "13:05"
cellTime.font = UIFont(name: "SourceSansPro-Semibold", size: 17.0)
contentView.addSubview(cellTime)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
51f54a715774cea88467fbe2469136f5
| 35.873016 | 150 | 0.671976 | 3.871667 | false | false | false | false |
wangwugang1314/weiBoSwift
|
weiBoSwift/weiBoSwift/Classes/Home/Controller/YBHomeController.swift
|
1
|
12762
|
//
// YBHomeController.swift
// weiBoSwift
//
// Created by MAC on 15/11/26.
// Copyright © 2015年 MAC. All rights reserved.
//
import UIKit
import SVProgressHUD
import MJRefresh
/// 数据加载类型
private enum YBHomeLoadDataStyle : Int {
case new
case old
}
class YBHomeController: YBBaseTableViewController {
// MARK: - 属性
private var dataArr: [YBWeiBoModel]? {
didSet{
// 更新数据
tableView.reloadData()
}
}
/// 记录动画是否完成(标记多少个更新数据)
private var isAnimationFinish = true
// MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// 如果是访客试图直接返回
if view is YBVisitView {
return
}
// 注册cell
tableView.registerClass(YBHomeTableViewCell.self, forCellReuseIdentifier: "YBHomeTableViewCell")
// 准备UI
prepareUI()
// 通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YBHomeController.homePopDismissedControllerNotification), name: YBHomePopDismissedControllerNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YBHomeController.homeCellImageClickNotification(_:)), name: YBHomeCellImageClickNotification, object: nil)
tableView.estimatedRowHeight = 400
// 加载用户数据
loadWeiBoData(YBHomeLoadDataStyle.new)
// 设置刷新控件
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[unowned self] () -> Void in
self.loadWeiBoData(YBHomeLoadDataStyle.new)
})
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[unowned self] () -> Void in
self.loadWeiBoData(YBHomeLoadDataStyle.old)
})
tableView.mj_header.beginRefreshing()
// 取消每行之间的分割线
tableView.separatorStyle = .None;
}
// MARK: - 加载微薄数据
private func loadWeiBoData(type: YBHomeLoadDataStyle) {
// 下拉加载新数据
var newId = 0
var oldId = 0
if type == .new && dataArr != nil{ // 上啦加载最新数据
newId = dataArr![0].Id
} else if type == .old {
oldId = dataArr!.last!.Id
}
YBWeiBoModel.loadWeiBoData(newId, max_id: oldId) {[unowned self] (dataArr, isError) -> () in
// 结束刷新控件
if type == .new{ // 上啦加载最新数据
self.tableView.mj_header.endRefreshing()
} else if type == .old {
self.tableView.mj_footer.endRefreshing()
}
if isError { // 数据加载出错
SVProgressHUD.showErrorWithStatus("数据加载出错")
}else{// 数据加载成功
if dataArr?.count != 0 { // 有新数据
// 判断记载数据的类型
switch type {
case .new:
if self.dataArr != nil {
self.dataArr?.insertContentsOf(dataArr!, at: 0)
}else{
self.dataArr = dataArr
}
case .old:
self.dataArr?.removeLast()
self.dataArr! += dataArr!;
}
self.showWeiBoNum.text = "加载了\(dataArr!.count)条微薄"
}else{ // 没有新数据
self.showWeiBoNum.text = "没有新微薄"
}
if type == .new {
// 如果正在动画就返回
self.showWeiBoNum.alpha = 0.8
if self.isAnimationFinish {
// 标记动画开始
self.isAnimationFinish = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.showWeiBoNum.frame = CGRect(x: 0, y: 44, width: UIScreen.width(), height: 40)
}, completion: { (_) -> Void in
UIView.animateWithDuration(0.5, delay: 1.2, usingSpringWithDamping: 0.4, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
self.showWeiBoNum.frame = CGRect(x: 0, y: 0, width: UIScreen.width(), height: 40)
}, completion: { (_) -> Void in
self.showWeiBoNum.alpha = 0
// 标记动画完成
self.isAnimationFinish = true
})
})
}
}
}
}
}
// MARK: - 通知
@objc private func homePopDismissedControllerNotification(){
titleViewClick(titleView)
}
@objc private func homeCellImageClickNotification(notification: NSNotification){
// 图片轮播器控制器
let vc = YBHomePictureShowController(model: notification.userInfo!["dataModel"] as! YBWeiBoModel)
// 设置弹出样式(后面的控制器不会消失)
vc.modalPresentationStyle = .Custom
presentViewController(vc, animated: true, completion: nil)
}
// MARK: - 准备UI
private func prepareUI(){
// 设置导航栏
setNavigationBar()
// 显示微薄条数
navigationController?.navigationBar.addSubview(showWeiBoNum)
navigationController?.navigationBar.sendSubviewToBack(showWeiBoNum)
showWeiBoNum.frame = CGRect(x: 0, y: -20, width: UIScreen.width(), height: 40)
}
/// 设置导航栏
private func setNavigationBar(){
// 左边
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigationbar_friendsearch"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YBHomeController.leftBarButtonItemClick))
// 右边
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigationbar_pop"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YBHomeController.rightBarButtonItemClick))
// 中间
navigationItem.titleView = titleView
}
// MARK: - 按钮点击
/// 导航栏左边按钮点击
@objc private func leftBarButtonItemClick(){
print("导航栏左边按钮点击\(self)")
}
/// 导航栏右边按钮点击
@objc private func rightBarButtonItemClick(){
presentViewController(YBNavScanCodeController(), animated: true, completion: nil)
}
/// 导航栏中间按钮点击
@objc private func titleViewClick(but: UIButton){
but.selected = !but.selected
if !but.selected {
let popVC = YBHomePopViewController()
// 设置弹出样式(后面的控制器不会消失)
popVC.modalPresentationStyle = .Custom
// 设置代理
popVC.transitioningDelegate = self
presentViewController(popVC, animated: true, completion: nil)
}
}
// MARK: - 行高
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let model = dataArr![indexPath.row]
return model.rowHeight ?? 700
}
/// 点击行不显示高亮
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: - 懒加载
/// 导航栏中间按钮
private lazy var titleView: YBHomeNavTitleView = {
let titleView = YBHomeNavTitleView()
// 添加点击事件
titleView.addTarget(self, action: #selector(YBHomeController.titleViewClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return titleView
}()
/// 显示加载微薄条数
private lazy var showWeiBoNum: UILabel = {
let view = UILabel()
view.backgroundColor = UIColor.orangeColor()
view.textAlignment = NSTextAlignment.Center
view.alpha = 0
return view
}()
}
/// 扩展、代理
extension YBHomeController: UIViewControllerTransitioningDelegate, YBHomeTableViewCellDelegate {
// MARK: - tableView数据源方法
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("YBHomeTableViewCell") as! YBHomeTableViewCell
// 如果是最后一行就加载
if indexPath.row == dataArr!.count - 1 {
loadWeiBoData(YBHomeLoadDataStyle.old)
}
cell.ybDelegate = self
// 设置数据
cell.data = dataArr![indexPath.row]
return cell
}
// MARK: - 专场动画代理
/// 展现代理(实现这个方法控制器试图需要自己手动添加)
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return YBHomePopPresentedController()
}
/// 消失代理
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return YBHomePopDismissedController()
}
/// 专场动画代理
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
return YBHomePresentationController(presentedViewController: presented, presentingViewController: presenting)
}
/// 点击网址调用
func homeTableViewCell(cell: YBHomeTableViewCell, pathStr: String) {
let vc = UINavigationController(rootViewController: YBHomeWebViewController(pathStr: pathStr))
presentViewController(vc, animated: true, completion: nil)
}
}
/// 展现代理
class YBHomePopPresentedController: NSObject, UIViewControllerAnimatedTransitioning {
/// 动画持续时间
@objc func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1.5
}
/// 动画
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let view = transitionContext.viewForKey(UITransitionContextToViewKey)
// 手动添加控制器试图
transitionContext.containerView()?.addSubview(view!)
// view动画
view?.transform = CGAffineTransformMakeScale(0.01, 0.01)
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
view?.transform = CGAffineTransformIdentity
}, completion: { (_) -> Void in
// 专场动画完一定告诉系统动画完成
transitionContext.completeTransition(true)
})
}
}
/// pop控制器消失通知
let YBHomePopDismissedControllerNotification = "YBHomePopDismissedControllerNotification"
/// 消失代理
class YBHomePopDismissedController: NSObject, UIViewControllerAnimatedTransitioning {
/// 动画持续时间
@objc func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1.5
}
/// 动画
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 旋转按钮(通知)
NSNotificationCenter.defaultCenter().postNotificationName(YBHomePopDismissedControllerNotification, object: nil)
// view动画
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
transitionContext.viewForKey(UITransitionContextFromViewKey)?.transform = CGAffineTransformMakeScale(0.001, 0.001)
transitionContext.containerView()?.alpha = 0
}, completion: { (_) -> Void in
// 专场动画完一定告诉系统动画完成
transitionContext.completeTransition(true)
})
}
}
|
apache-2.0
|
d773f94c3b008f779bdab5a060f104ff
| 34.815152 | 220 | 0.615873 | 5.238918 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper
|
Sources/TMDBSwift/Models/Company.swift
|
1
|
767
|
import Foundation
/// <#Description#>
public struct Company: Codable, Equatable {
/// <#Description#>
public var id: Int
/// <#Description#>
public var logoPath: String?
/// <#Description#>
public var name: String?
/// <#Description#>
public var originCountry: String? // change to enum?
public init(id: Int,
logoPath: String? = nil,
name: String? = nil,
originCountry: String? = nil) {
self.id = id
self.logoPath = logoPath
self.name = name
self.originCountry = originCountry
}
enum CodingKeys: String, CodingKey {
case id
case logoPath = "logo_path"
case name
case originCountry = "origin_country"
}
}
|
mit
|
e60422e5b93424c1cca9638618f23fb9
| 24.566667 | 56 | 0.563233 | 4.382857 | false | false | false | false |
jorgeluis11/EmbalsesPR
|
Embalses/backup.swift
|
1
|
7837
|
////
//// EmbalsesTableViewController.swift
//// Embalses
////
//// Created by Jorge Perez on 9/29/15.
//// Copyright © 2015 Jorge Perez. All rights reserved.
////
//
//import UIKit
//import Kanna
//
//class EmbalsesTableViewController: UITableViewController,UIBarPositioningDelegate {
//
// var myNewDictArray:[Dictionary<Int, String>] = []
// var nextScreenRow:Int = 0
// var date:String = ""
//
// @IBOutlet var embalsesTable: UITableView!
//
// func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
// return .TopAttached
// }
//
// override func viewWillAppear(animated: Bool) {
//
// // let url = NSURL(string: "http://waterdata.usgs.gov/pr/nwis/current/?type=lake_m&group_key=NONE")
// let url = NSURL(string: "http://acueductospr.com/AAARepresas/reservoirlist")
// let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
// (NSString(data: data!, encoding: NSUTF8StringEncoding))
//
// let x:String = (NSString(data: data!, encoding: NSUTF8StringEncoding)) as! String
// //
// // if let name = aDecoder.decodeObjectForKey(x) as? NSString {
// // self.name = name as String
// // } else {
// // assert(false, "ERROR: could not decode")
// // self.name = "ERROR"
// // }
// //
// // var i:Int = 0
// // var arrayI = 0
// //
// //
// if let doc = Kanna.HTML(html: x, encoding: NSUTF8StringEncoding) {
// var dictionary = [0:"",1:"",2:"",3:""]
// // var inode = 0
// self.date = doc.css(".sec-intro").text!
// var index = 1
// for link in doc.css(".reservoir.reservoirBox") {
// // if i >= 2
// // {
//
// if let itemHtml = Kanna.HTML(html: link.innerHTML!, encoding: NSUTF8StringEncoding) {
//
// let name:String = itemHtml.css(".locationLevel").innerHTML!
// let info = name.componentsSeparatedByString(": ")
// dictionary[0] = info[0]
// dictionary[1] = info[1]
// dictionary[2] = "http://acueductospr.com/AAARepresas/reservoir?i=" + String(index)
// index++
// self.myNewDictArray.append(dictionary)
//
// }
//
// }
// }
//
// dispatch_async(dispatch_get_main_queue(), {
// self.tableView.reloadData()
// });
// }
//
// task.resume()
//
//
//
//
// }
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
//
//
// // Uncomment the following line to preserve selection between presentations
// // self.clearsSelectionOnViewWillAppear = false
//
// // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// // self.navigationItem.rightBarButtonItem = self.editButtonItem()
//
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// // 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
// // self.r
// return myNewDictArray.count
// }
//
//
// override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("tableContent", forIndexPath: indexPath) as! EmbalsesTableViewCell
//
// let embalsesInfo = myNewDictArray[indexPath.row]
//
// cell.pueblo.text = "San Juan"
// cell.embalse.text = embalsesInfo[1]
// cell.fecha.text = embalsesInfo[2]
// cell.metros.text = embalsesInfo[3]
//
// return cell
// }
//
// override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//
// // self.performSegueWithIdentifier("detail_segue", sender: self)
// self.nextScreenRow = indexPath.row
// self.performSegueWithIdentifier("detail_segue", sender: self)
//
//
// }
//
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
//
// // if (segue.identifier == "detail_segue") {
// // let embalsesInfo = myNewDictArray[]
//
// // var destinationVC:DetailViewController = segue.destinationViewController
//
// //
//
// let detailController = segue.destinationViewController as! DetailViewController;
//
// detailController.county = myNewDictArray[nextScreenRow][1]!
// detailController.date = myNewDictArray[nextScreenRow][2]!
// detailController.meters = myNewDictArray[nextScreenRow][3]!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
//
// print(detailController)
// // }
//
// }// end prepareForSegue
//
// /*
// // Override to support conditional editing of the table view.
// override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// // Return false if you do not want the specified item to be editable.
// return true
// }
// */
//
// /*
// // Override to support editing the table view.
// override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// if editingStyle == .Delete {
// // Delete the row from the data source
// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// } else if editingStyle == .Insert {
// // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
// }
// }
// */
//
// /*
// // Override to support rearranging the table view.
// override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
//
// }
// */
//
// /*
// // Override to support conditional rearranging of the table view.
// override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// // Return false if you do not want the item to be re-orderable.
// return true
// }
// */
//
// /*
// // MARK: - Navigation
//
// // In a storyboard-based application, you will often want to do a little preparation before navigation
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// // Get the new view controller using segue.destinationViewController.
// // Pass the selected object to the new view controller.
// }
// */
//
//}
|
mit
|
2218bb4f3c3e4a0db10811de0697decc
| 38.18 | 159 | 0.556406 | 4.277293 | false | false | false | false |
gribozavr/swift
|
test/Constraints/function_builder_diags.swift
|
1
|
7156
|
// RUN: %target-typecheck-verify-swift -disable-availability-checking
@_functionBuilder
struct TupleBuilder { // expected-note 2{{struct 'TupleBuilder' declared here}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
}
@_functionBuilder
struct TupleBuilderWithoutIf { // expected-note {{struct 'TupleBuilderWithoutIf' declared here}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
func tuplifyWithoutIf<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) {
print(body(cond))
}
func testDiags() {
// For loop
tuplify(true) { _ in
17
for c in name { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilder'}}
// expected-error@-1 {{use of unresolved identifier 'name'}}
}
}
// Declarations
tuplify(true) { _ in
17
let x = 17 // expected-error{{closure containing a declaration cannot be used with function builder 'TupleBuilder'}}
x + 25
}
// Statements unsupported by the particular builder.
tuplifyWithoutIf(true) {
if $0 { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilderWithoutIf'}}
"hello"
}
}
}
struct A { }
struct B { }
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) -> A { // expected-note {{found this candidate}}
return A()
}
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) -> B { // expected-note {{found this candidate}}
return B()
}
func testOverloading(name: String) {
let a1 = overloadedTuplify(true) { b in
if b {
"Hello, \(name)"
}
}
let _: A = a1
_ = overloadedTuplify(true) { b in // expected-error {{ambiguous use of 'overloadedTuplify(_:body:)'}}
b ? "Hello, \(name)" : "Goodbye"
42
overloadedTuplify(false) {
$0 ? "Hello, \(name)" : "Goodbye"
42
if $0 {
"Hello, \(name)"
}
}
}
}
protocol P {
associatedtype T
}
struct AnyP : P {
typealias T = Any
init<T>(_: T) where T : P {}
}
struct TupleP<U> : P {
typealias T = U
init(_: U) {}
}
@_functionBuilder
struct Builder {
static func buildBlock<S0, S1>(_ stmt1: S0, _ stmt2: S1) // expected-note {{required by static method 'buildBlock' where 'S1' = 'Label<_>.Type'}}
-> TupleP<(S0, S1)> where S0: P, S1: P {
return TupleP((stmt1, stmt2))
}
}
struct G<C> : P where C : P {
typealias T = C
init(@Builder _: () -> C) {}
}
struct Text : P {
typealias T = String
init(_: T) {}
}
struct Label<L> : P where L : P { // expected-note 2 {{'L' declared as parameter to type 'Label'}}
typealias T = L
init(@Builder _: () -> L) {} // expected-note {{'init(_:)' declared here}}
}
func test_51167632() -> some P {
AnyP(G { // expected-error {{type 'Label<_>.Type' cannot conform to 'P'; only struct/enum/class types can conform to protocols}}
Text("hello")
Label // expected-error {{generic parameter 'L' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}}
})
}
func test_56221372() -> some P {
AnyP(G {
Text("hello")
Label() // expected-error {{generic parameter 'L' could not be inferred}}
// expected-error@-1 {{missing argument for parameter #1 in call}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}}
})
}
struct SR11440 {
typealias ReturnsTuple<T> = () -> (T, T)
subscript<T, U>(@TupleBuilder x: ReturnsTuple<T>) -> (ReturnsTuple<U>) -> Void { //expected-note {{in call to 'subscript(_:)'}}
return { _ in }
}
func foo() {
// This is okay, we apply the function builder for the subscript arg.
self[{
5
5
}]({
(5, 5)
})
// But we shouldn't perform the transform for the argument to the call
// made on the function returned from the subscript.
self[{ // expected-error {{generic parameter 'U' could not be inferred}}
5
5
}]({
5
5
})
}
}
func acceptInt(_: Int, _: () -> Void) { }
// SR-11350 crash due to improper recontextualization.
func erroneousSR11350(x: Int) {
tuplify(true) { b in
17
x + 25
Optional(tuplify(false) { b in
if b {
acceptInt(0) { }
}
}).domap(0) // expected-error{{value of type '()?' has no member 'domap'}}
}
}
func extraArg() {
tuplify(true) { _ in
1
2
3
4
5
6 // expected-error {{extra argument in call}}
}
}
// rdar://problem/53209000 - use of #warning and #error
tuplify(true) { x in
1
#error("boom") // expected-error{{boom}}
"hello"
#warning("oops") // expected-warning{{oops}}
3.14159
}
struct MyTuplifiedStruct {
var condition: Bool
@TupleBuilder var computed: some Any { // expected-note{{remove the attribute to explicitly disable the function builder}}{{3-17=}}
if condition {
return 17 // expected-warning{{application of function builder 'TupleBuilder' disabled by explicit 'return' statement}}
// expected-note@-1{{remove 'return' statements to apply the function builder}}{{7-14=}}{{12-19=}}
} else {
return 42
}
}
}
// Check that we're performing syntactic use diagnostics/
func acceptMetatype<T>(_: T.Type) -> Bool { true }
func syntacticUses<T>(_: T) {
tuplify(true) { x in
if x && acceptMetatype(T) { // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}
acceptMetatype(T) // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}
}
}
}
|
apache-2.0
|
6ea082bac7c652c0221dfa478215ffa4
| 25.405904 | 147 | 0.593907 | 3.163572 | false | false | false | false |
terietor/GTForms
|
Example/TestKeyboardTableViewController.swift
|
1
|
2551
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import GTForms
class TestKeyboardTableViewController: FormTableViewController {
fileprivate lazy var hideKeyboardButton: UIBarButtonItem = {
let button = UIBarButtonItem(
title: "Hide Keyboard",
style: .done,
target: self,
action: #selector(didTapHideKeyboardButton)
)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.hideKeyboardButton
let selectionItems = [
SelectionFormItem(text: "Apple"),
SelectionFormItem(text: "Orange")
]
let selectionForm = SelectionForm(
items: selectionItems,
text: "Choose a fruit"
)
selectionForm.textColor = UIColor.red
selectionForm.textFont = UIFont
.preferredFont(forTextStyle: UIFontTextStyle.headline)
selectionForm.allowsMultipleSelection = true
let section = FormSection()
section.addRow(selectionForm)
section.addRow(FormDatePicker(text: "Date Picker"))
section.addRow(FormDoubleTextField(
text: "Double Form",
placeHolder: "Type a double")
)
self.formSections.append(section)
}
@objc fileprivate func didTapHideKeyboardButton() {
hideKeyboard()
}
}
|
mit
|
c18918e32f8a72b1ac0dccf1826562a0
| 33.945205 | 82 | 0.687574 | 4.896353 | false | false | false | false |
arinjoy/Landmark-Remark
|
LandmarkRemark/LandmarkRemarkService.swift
|
1
|
11231
|
//
// LandmarkRemarkService.swift
// LandmarkRemark
//
// Created by Arinjoy Biswas on 6/06/2016.
// Copyright © 2016 Arinjoy Biswas. All rights reserved.
//
import Parse
/// The service to apply CRUD (Create/Read/Update/Delete) operations on landmark objects saved on Parse backend
class LandmarkRemarkService {
/**
To retrieve all the landmarks object saved by different users, loading from the Parse backend
- parameter currentLocation: The current geo-location of the device to calculate the distance information
- parameter withinDistance: The distance in kilometres to sarch for other landmarks from the current device location
- parameter completionHandler: The completion block after asynchronous network call - to return the list of landmarks
*/
func retrieveAllLandmarks(currentLocation currentLocation: CLLocation? = nil, withinDistance: Double? = nil, completionHandler: (landmarks: [Landmark], error: NSError?) -> Void) {
var landmarkResults:[Landmark] = [Landmark]()
let query = PFQuery(className: "Landmark")
// Parse limit is 1000, so reduce the limit to 900
query.limit = 900
// Always try to load from network first and if not connected then from device cache
query.cachePolicy = .NetworkElseCache
// Inlcude the user objects who saved the landmark
query.includeKey("savedBy")
if currentLocation != nil {
let currentPoint = PFGeoPoint(location: currentLocation)
// If the current device location is specified, then check whther distance radius is also specified
// Apply geo-spatial query supported by Parse
if withinDistance != nil {
query.whereKey("location", nearGeoPoint: currentPoint, withinKilometers: withinDistance!)
} else {
// search the entire planet with 360 degree in radian
query.whereKey("location", nearGeoPoint: currentPoint, withinRadians: 6.28318)
}
}
else {
// by default order using the note text content, if no geo-spatial query is applied
query.orderByAscending("note")
}
query.findObjectsInBackgroundWithBlock { (objects, error) in
if error == nil {
if let landmarks = objects {
for landmark in landmarks {
var distanceText: String? = nil
let geoPoint = landmark["location"] as! PFGeoPoint
// if current location is known, calculate the distance info to display as a hint
if currentLocation != nil {
let distance = PFGeoPoint(location: currentLocation).distanceInKilometersTo(geoPoint)
distanceText = self.generateDistanceHint(distance)
}
// convert the Parse landmark object to the data model and then append that into the list
landmarkResults.append(Landmark(dict: ServiceHelper.convertLandmarkObjectToDictionary(landmark), distance: distanceText))
}
}
completionHandler(landmarks: landmarkResults, error: nil)
}
else {
completionHandler(landmarks: landmarkResults, error: error)
}
}
}
/**
To create a landmark object on the Parse backend
- parameter user: The user who is saving this landmark
- parameter note: The remark/note for the landmark
- parameter location: The geo-location whther landmark is being added by the user
- parameter completionHandler: The completion block after asynchronous network call - to return the created landmark instance or failure with reasons
*/
func createLandmark(user: PFUser, note: String, location: CLLocationCoordinate2D, completionHandler: (landmark: Landmark?, error: NSError?) -> Void) {
let newlandmark = PFObject(className:"Landmark")
newlandmark["savedBy"] = user
newlandmark["note"] = note
newlandmark["location"] = PFGeoPoint(latitude: location.latitude, longitude: location.longitude)
newlandmark.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if success {
// convert the Parse landmark object to data model
let resultLandmark = Landmark(dict: ServiceHelper.convertLandmarkObjectToDictionary(newlandmark), distance: "0 m away")
completionHandler(landmark: resultLandmark, error: nil)
}
else {
completionHandler(landmark: nil, error: error)
}
}
}
/**
To update a landmark object, i.e. to change the note text. Only the owner (who save it) can edit the note
- parameter landmarkId: The id of the landmark to be updated
- parameter newNote: The new note to be updated
- parameter currentLocation: The current location of the user
- parameter completionHandler: The completion block after asynchronous network call - to return the updated landmark instance or failure with reasons
*/
func updateLandmark(landmarkId: String, newNote: String, currentLocation: CLLocation?, completionHandler: (landmark: Landmark?, error: NSError?) -> Void) {
let query = PFQuery(className: "Landmark")
query.limit = 1
query.cachePolicy = .NetworkElseCache
// match the landmark object Id
query.whereKey("objectId", equalTo: landmarkId)
query.includeKey("savedBy")
// find the object first
query.findObjectsInBackgroundWithBlock { (objects, loadError) in
if loadError == nil {
if let objects = objects {
// must return a single object
if objects.count == 1 {
let targetLandmark = objects[0]
targetLandmark["note"] = newNote
// saving back the new value
targetLandmark.saveInBackgroundWithBlock({ (success, error) in
if success {
var distanceText: String? = nil
// calculate the distance info
if currentLocation != nil {
let geoPoint = targetLandmark["location"] as! PFGeoPoint
let distance = PFGeoPoint(location: currentLocation).distanceInKilometersTo(geoPoint)
distanceText = self.generateDistanceHint(distance)
}
let resultLandmark = Landmark(dict: ServiceHelper.convertLandmarkObjectToDictionary(targetLandmark), distance: distanceText)
completionHandler(landmark: resultLandmark, error: nil)
}
else {
completionHandler(landmark: nil, error: error)
}
})
}
else {
// if no object was found and error is not nil either - this would never happen unless Parse gives incorrect structure
completionHandler(landmark: nil, error: NSError(domain: "Landmark.domain", code: 503, userInfo: nil))
}
}
else {
// if no object was found and error is not nil either - this would never happen unless Parse gives incorrect structure
completionHandler(landmark: nil, error: NSError(domain: "Landmark.domain", code: 503, userInfo: nil))
}
}
else {
completionHandler(landmark: nil, error: loadError)
}
}
}
/**
To delete a lanmark object by its owner only
- parameter landmarkId: The object id of the landmark
- parameter completionHanlder: The completion block after asynchronous network call - to indicate success or failure
*/
func deleteLandmark(landmarkId: String, completionHanlder: (success: Bool, error: NSError?) -> Void) {
let query = PFQuery(className: "Landmark")
query.limit = 1
query.cachePolicy = .NetworkElseCache
// match the object using the object Id
query.whereKey("objectId", equalTo: landmarkId)
query.findObjectsInBackgroundWithBlock { (objects, loadError) in
if loadError == nil {
if let objects = objects {
if objects.count == 1 {
let targetLandmark = objects[0]
targetLandmark.deleteInBackgroundWithBlock({ (success, deleteError) in
completionHanlder(success: success, error: deleteError)
})
}
else {
// if no object was found and error is not nil either - this would never happen unless Parse gives incorrect structure
completionHanlder(success: false, error: NSError(domain: "Landmark.domain", code: 505, userInfo: nil))
}
}
else {
// if no object was found and error is not nil either - this would never happen unless Parse gives incorrect structure
completionHanlder(success: false, error: NSError(domain: "Landmark.domain", code: 505, userInfo: nil))
}
}
else {
completionHanlder(success: false, error: loadError)
}
}
}
//----------------------------
// MARK: - Private Helpers
//----------------------------
/**
A helper method to calcuate the ditance hint
- parameter distance: The distance in kilometres
- returns: The textual information to display in the UI
*/
func generateDistanceHint(distance: Double) -> String {
// if withing one km, check for less than 5m, 20m or 50m
if distance < 1.0 {
if distance * 1000 <= 5.0 {
return "just here"
}
else if distance * 1000 <= 20.0 {
return "less than 20 m away"
}
else if distance * 1000 <= 50.0 {
return "less than 50 m away"
}
else {
// if more than 50m, show the real distance
return "\(Double(round(10 * distance * 1000) / 10)) m away"
}
}
else {
// show the km after rounding 2 deciamal points
return "\(Double(round(100 * distance) / 100)) km away"
}
}
}
|
mit
|
c55e8edd2b55ae0ccd598f49b2f192e7
| 44.465587 | 183 | 0.561799 | 5.575968 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/ChatsControllers/UserInfoTableViewController.swift
|
1
|
9741
|
//
// UserInfoTableViewController.swift
// Pigeon-project
//
// Created by Roman Mizin on 10/18/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import Firebase
private let headerCellIdentifier = "headerCellIdentifier"
private let phoneNumberCellIdentifier = "phoneNumberCellIdentifier"
private let bioCellIdentifier = "bioCellIdentifier"
private let adminControlsCellID = "adminControlsCellID"
protocol UserBlockDelegate: class {
func blockUser(with uid: String)
}
class UserInfoTableViewController: UITableViewController {
var user: User? {
didSet {
contactPhoneNumber = user?.phoneNumber ?? ""
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
var conversationID = String()
var onlineStatus = String()
var contactPhoneNumber = String()
var userReference: DatabaseReference!
var handle: DatabaseHandle!
var shouldDisplayContactAdder: Bool?
private var observer: NSObjectProtocol!
weak var delegate: UserBlockDelegate?
let adminControls = ["Shared Media", "Block User"]
override func viewDidLoad() {
super.viewDidLoad()
setupMainView()
setupTableView()
getUserInfo()
addObservers()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.navigationController?.visibleViewController is SharedMediaController {
return
}
if userReference != nil {
userReference.removeObserver(withHandle: handle)
}
}
deinit {
print("user info deinit")
NotificationCenter.default.removeObserver(observer as Any)
}
fileprivate func addObservers() {
observer = NotificationCenter.default.addObserver(forName: .localPhonesUpdated,
object: nil,
queue: .main) { [weak self] _ in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
fileprivate func setupMainView() {
title = "Info"
extendedLayoutIncludesOpaqueBars = true
view.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .always
}
}
fileprivate func setupTableView() {
tableView.separatorStyle = .none
tableView.register(UserinfoHeaderTableViewCell.self, forCellReuseIdentifier: headerCellIdentifier)
tableView.register(UserInfoPhoneNumberTableViewCell.self, forCellReuseIdentifier: phoneNumberCellIdentifier)
tableView.register(GroupAdminPanelTableViewCell.self, forCellReuseIdentifier: adminControlsCellID)
}
fileprivate func getUserInfo() {
userReference = Database.database().reference().child("users").child(conversationID)
handle = userReference.observe(.value) { (snapshot) in
if snapshot.exists() {
guard var dictionary = snapshot.value as? [String: AnyObject] else { return }
dictionary.updateValue(snapshot.key as AnyObject, forKey: "id")
self.user = User(dictionary: dictionary)
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 {
return adminControls.count
}
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 100
} else if indexPath.section == 2 {
return 130
} else {
return 60
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let phoneNumberCell = tableView.cellForRow(at: IndexPath(row: 0, section: 2)) as? UserInfoPhoneNumberTableViewCell ?? UserInfoPhoneNumberTableViewCell()
if globalVariables.localPhones.contains(contactPhoneNumber.digits) {
phoneNumberCell.add.isHidden = true
phoneNumberCell.contactStatus.isHidden = true
phoneNumberCell.addHeightConstraint.constant = 0
phoneNumberCell.contactStatusHeightConstraint.constant = 0
} else {
phoneNumberCell.add.isHidden = false
phoneNumberCell.contactStatus.isHidden = false
phoneNumberCell.addHeightConstraint.constant = 40
phoneNumberCell.contactStatusHeightConstraint.constant = 40
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let headerCell = tableView.dequeueReusableCell(withIdentifier: headerCellIdentifier,
for: indexPath) as? UserinfoHeaderTableViewCell ?? UserinfoHeaderTableViewCell()
headerCell.title.text = user?.name ?? ""
headerCell.title.font = UIFont.boldSystemFont(ofSize: 20)
headerCell.subtitle.text = user?.onlineStatusString
if user?.onlineStatusString == statusOnline {
headerCell.subtitle.textColor = view.tintColor
} else {
headerCell.subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor
}
headerCell.selectionStyle = .none
guard let photoURL = user?.thumbnailPhotoURL else {
headerCell.icon.image = UIImage(named: "UserpicIcon")
return headerCell
}
headerCell.icon.showActivityIndicator()
headerCell.icon.sd_setImage(with: URL(string: photoURL),
placeholderImage: UIImage(named: "UserpicIcon"),
options: [.continueInBackground, .scaleDownLargeImages],
completed: { (_, error, _, _) in
headerCell.icon.hideActivityIndicator()
guard error == nil else { return }
headerCell.icon.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.openPhoto)))
})
return headerCell
} else if indexPath.section == 2 {
let phoneNumberCell = tableView.dequeueReusableCell(withIdentifier: phoneNumberCellIdentifier,
for: indexPath) as? UserInfoPhoneNumberTableViewCell ?? UserInfoPhoneNumberTableViewCell()
phoneNumberCell.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
phoneNumberCell.userInfoTableViewController = self
if globalVariables.localPhones.contains(contactPhoneNumber.digits) {
phoneNumberCell.add.isHidden = true
phoneNumberCell.contactStatus.isHidden = true
phoneNumberCell.addHeightConstraint.constant = 0
phoneNumberCell.contactStatusHeightConstraint.constant = 0
} else {
phoneNumberCell.add.isHidden = false
phoneNumberCell.contactStatus.isHidden = false
phoneNumberCell.addHeightConstraint.constant = 40
phoneNumberCell.contactStatusHeightConstraint.constant = 40
}
var phoneTitle = "mobile\n"
let phoneBody = user?.phoneNumber ?? ""
if phoneBody == "" || phoneBody == " " { phoneTitle = "" }
phoneNumberCell.phoneLabel.attributedText = setAttributedText(title: phoneTitle, body: phoneBody)
var bioTitle = "bio\n"
let bioBody = user?.bio ?? ""
if bioBody == "" || bioBody == " " { bioTitle = "" }
phoneNumberCell.bio.attributedText = setAttributedText(title: bioTitle, body: bioBody)
return phoneNumberCell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: adminControlsCellID,
for: indexPath) as? GroupAdminPanelTableViewCell ?? GroupAdminPanelTableViewCell()
cell.selectionStyle = .none
cell.button.setTitle(adminControls[indexPath.row], for: .normal)
cell.button.setTitleColor(cell.button.title(for: .normal) == adminControls.last ? FalconPalette.dismissRed : cell.button.currentTitleColor, for: .normal)
cell.button.addTarget(self, action: #selector(controlButtonClicked(_:)), for: .touchUpInside)
return cell
}
}
func setAttributedText(title: String, body: String) -> NSAttributedString {
let mutableAttributedString = NSMutableAttributedString()
let titleAttributes = [NSAttributedString.Key.foregroundColor: view.tintColor,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)]
let bodyAttributes = [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalTitleColor,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]
let titleAttributedString = NSAttributedString(string: title, attributes: titleAttributes as [NSAttributedString.Key : Any])
let bodyAttributedString = NSAttributedString(string: body, attributes: bodyAttributes)
mutableAttributedString.append(titleAttributedString)
mutableAttributedString.append(bodyAttributedString)
return mutableAttributedString
}
@objc fileprivate func controlButtonClicked(_ sender: UIButton) {
guard let superview = sender.superview, let currentUserID = Auth.auth().currentUser?.uid else { return }
let point = tableView.convert(sender.center, from: superview)
guard let indexPath = tableView.indexPathForRow(at: point),
indexPath.section == 1 else {
return
}
if indexPath.row == 0 {
let destination = SharedMediaController(collectionViewLayout: UICollectionViewFlowLayout())
destination.conversation = RealmKeychain.defaultRealm.object(ofType: Conversation.self, forPrimaryKey: conversationID)
destination.fetchingData = (userID: currentUserID, chatID: conversationID)
navigationController?.pushViewController(destination, animated: true)
} else {
delegate?.blockUser(with: conversationID)
}
}
}
|
gpl-3.0
|
fb3d908a9f0b65615678da9e3f02b27b
| 37.498024 | 156 | 0.702259 | 5.096808 | false | false | false | false |
ahoppen/swift
|
test/SILGen/unsafevalue.swift
|
3
|
8152
|
// RUN: %target-swift-emit-silgen -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
// RUN: %target-swift-emit-sil -Onone -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=CANONICAL %s
// RUN: %target-swift-emit-sil -O -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=OPT %s
import Swift
// Eventually element will be unconstrained, but for testing this builtin, we
// should use it this way.
@frozen
public struct UnsafeValue<Element: AnyObject> {
@usableFromInline
internal unowned(unsafe) var _value: Element
// Create a new unmanaged value that owns the underlying value. This unmanaged
// value must after use be deinitialized by calling the function deinitialize()
//
// This will insert a retain that the optimizer can not remove!
@_transparent
@inlinable
public init(copying newValue: __shared Element) {
Builtin.retain(newValue)
_value = newValue
}
// Create a new unmanaged value that unsafely produces a new
// unmanaged value without introducing any rr traffic.
//
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC : $@convention(method) <Element where Element : AnyObject> (@guaranteed Element, @thin UnsafeValue<Element>.Type) -> UnsafeValue<Element> {
// CHECK: bb0([[INPUT_ELEMENT:%.*]] : @guaranteed $Element,
// CHECK: [[BOX:%.*]] = alloc_box
// CHECK: [[UNINIT_BOX:%.*]] = mark_uninitialized [rootself] [[BOX]]
// CHECK: [[UNINIT_BOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[UNINIT_BOX]]
// CHECK: [[PROJECT_UNINIT_BOX:%.*]] = project_box [[UNINIT_BOX_LIFETIME]]
// CHECK: [[COPY_INPUT_ELEMENT:%.*]] = copy_value [[INPUT_ELEMENT]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[PROJECT_UNINIT_BOX]]
// CHECK: [[STRUCT_ACCESS:%.*]] = struct_element_addr [[ACCESS]]
// CHECK: [[UNMANAGED_INPUT_ELEMENT:%.*]] = ref_to_unmanaged [[COPY_INPUT_ELEMENT]]
// CHECK: assign [[UNMANAGED_INPUT_ELEMENT]] to [[STRUCT_ACCESS]]
// CHECK: destroy_value [[COPY_INPUT_ELEMENT]]
// CHECK: end_access [[ACCESS]]
// CHECK: [[RESULT:%.*]] = load [trivial] [[PROJECT_UNINIT_BOX]]
// CHECK: end_borrow [[UNINIT_BOX_LIFETIME]]
// CHECK: destroy_value [[UNINIT_BOX]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC'
//
// CANONICAL-LABEL: sil [transparent] @$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC : $@convention(method) <Element where Element : AnyObject> (@guaranteed Element, @thin UnsafeValue<Element>.Type) -> UnsafeValue<Element> {
// CANONICAL: bb0([[INPUT_ELEMENT:%.*]] : $Element,
// CANONICAL-NEXT: debug_value
// CANONICAL-NEXT: strong_retain [[INPUT_ELEMENT]]
// CANONICAL-NEXT: [[UNMANAGED_ELEMENT:%.*]] = ref_to_unmanaged [[INPUT_ELEMENT]]
// CANONICAL-NEXT: strong_release [[INPUT_ELEMENT]]
// CANONICAL-NEXT: [[RESULT:%.*]] = struct $UnsafeValue<Element> ([[UNMANAGED_ELEMENT]] : $@sil_unmanaged Element)
// CANONICAL-NEXT: return [[RESULT]]
// CANONICAL: } // end sil function '$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC'
//
// OPT-LABEL: sil [transparent] @$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC : $@convention(method) <Element where Element : AnyObject> (@guaranteed Element, @thin UnsafeValue<Element>.Type) -> UnsafeValue<Element> {
// OPT: bb0([[INPUT_ELEMENT:%.*]] : $Element,
// OPT-NEXT: debug_value
// OPT-NEXT: [[UNMANAGED_ELEMENT:%.*]] = ref_to_unmanaged [[INPUT_ELEMENT]]
// OPT-NEXT: [[RESULT:%.*]] = struct $UnsafeValue<Element> ([[UNMANAGED_ELEMENT]] : $@sil_unmanaged Element)
// OPT-NEXT: return [[RESULT]]
// OPT: } // end sil function '$s11unsafevalue11UnsafeValueV14unsafelyAssignACyxGxh_tcfC'
@_transparent
@inlinable
public init(unsafelyAssign newValue: __shared Element) {
_value = newValue
}
// Access the underlying value at +0, guaranteeing its lifetime by base.
//
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF :
// CHECK: bb0([[RESULT:%.*]] : $*Result, [[BASE:%.*]] : $*Base, [[CLOSURE:%.*]] : $@noescape @callee_guaranteed {{.*}}, [[UNSAFE_VALUE:%.*]] : $UnsafeValue<Element>):
// CHECK: [[COPY_BOX:%.*]] = alloc_box
// CHECK: [[COPY_BOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[COPY_BOX]]
// CHECK: [[COPY_PROJ:%.*]] = project_box [[COPY_BOX_LIFETIME]]
// CHECK: store [[UNSAFE_VALUE]] to [trivial] [[COPY_PROJ]]
// CHECK: [[VALUE_ADDR:%.*]] = begin_access [read] [unknown] [[COPY_PROJ]]
// CHECK: [[STR_VALUE_ADDR:%.*]] = struct_element_addr [[VALUE_ADDR]]
// CHECK: [[UNMANAGED_VALUE:%.*]] = load [trivial] [[STR_VALUE_ADDR]]
// CHECK: [[UNOWNED_REF:%.*]] = unmanaged_to_ref [[UNMANAGED_VALUE]]
// CHECK: [[GUARANTEED_REF:%.*]] = unchecked_ownership_conversion [[UNOWNED_REF]]
// CHECK: [[GUARANTEED_REF_DEP_ON_BASE:%.*]] = mark_dependence [[GUARANTEED_REF]] : $Element on [[BASE]]
// CHECK: end_access [[VALUE_ADDR]]
// CHECK: apply [[CLOSURE]]([[RESULT]], [[GUARANTEED_REF_DEP_ON_BASE]])
// CHECK: end_borrow [[GUARANTEED_REF]]
// CHECK: end_borrow [[COPY_BOX_LIFETIME]]
// CHECK: destroy_value [[COPY_BOX]]
// CHECK: } // end sil function '$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF'
//
// CANONICAL-LABEL: sil [transparent] @$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF :
// CANONICAL: bb0([[RESULT:%.*]] : $*Result, [[BASE:%.*]] : $*Base, [[CLOSURE:%.*]] : $@noescape @callee_guaranteed {{.*}}, [[UNSAFE_VALUE:%.*]] : $UnsafeValue<Element>):
// CANONICAL: [[UNMANAGED_VALUE:%.*]] = struct_extract [[UNSAFE_VALUE]]
// CANONICAL: [[UNOWNED_REF:%.*]] = unmanaged_to_ref [[UNMANAGED_VALUE]]
// CANONICAL: [[GUARANTEED_REF_DEP_ON_BASE:%.*]] = mark_dependence [[UNOWNED_REF]] : $Element on [[BASE]]
// CANONICAL: apply [[CLOSURE]]([[RESULT]], [[GUARANTEED_REF_DEP_ON_BASE]])
// CANONICAL: } // end sil function '$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF'
//
// OPT-LABEL: sil [transparent] {{.*}}@$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF :
// OPT: bb0([[RESULT:%.*]] : $*Result, [[BASE:%.*]] : $*Base, [[CLOSURE:%.*]] : $@noescape @callee_guaranteed {{.*}}, [[UNSAFE_VALUE:%.*]] : $UnsafeValue<Element>):
// OPT: [[UNMANAGED_VALUE:%.*]] = struct_extract [[UNSAFE_VALUE]]
// OPT: [[UNOWNED_REF:%.*]] = unmanaged_to_ref [[UNMANAGED_VALUE]]
// OPT: [[GUARANTEED_REF_DEP_ON_BASE:%.*]] = mark_dependence [[UNOWNED_REF]] : $Element on [[BASE]]
// OPT: apply [[CLOSURE]]([[RESULT]], [[GUARANTEED_REF_DEP_ON_BASE]])
// OPT: } // end sil function '$s11unsafevalue11UnsafeValueV20withGuaranteeingBase4base_qd_0_qd___qd_0_xXEtr0_lF'
@_transparent
@inlinable
func withGuaranteeingBase<Base, Result>(base: Base, _ f: (Element) -> Result) -> Result {
// Just so we can not mark self as mutating. This is just a bitwise copy.
var tmp = self
return f(Builtin.convertUnownedUnsafeToGuaranteed(base, &tmp._value))
}
@_transparent
@inlinable
func assumingGuaranteeingBase<Result>(_ f: (Element) -> Result) -> Result {
// Just so we can not mark self as mutating. This is just a bitwise copy.
let fakeBase: Int? = nil
return withGuaranteeingBase(base: fakeBase, f)
}
// If the unmanaged value was initialized with a copy, release the underlying value.
//
// This will insert a release that can not be removed by the optimizer.
@_transparent
@inlinable
mutating func deinitialize() {
Builtin.release(_value)
}
// Return a new strong reference to the unmanaged value.
//
// This will insert a retain that can not be removed by the optimizer!
@_transparent
@inlinable
public var strongRef: Element { _value }
}
|
apache-2.0
|
de21a4e85027811d1098e7c188db722a
| 58.50365 | 254 | 0.67186 | 3.491221 | false | false | false | false |
kunitoku/RssReader
|
Pods/RealmSwift/RealmSwift/Results.swift
|
9
|
16815
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
// MARK: MinMaxType
/**
Types of properties which can be used with the minimum and maximum value APIs.
- see: `min(ofProperty:)`, `max(ofProperty:)`
*/
public protocol MinMaxType {}
extension NSNumber: MinMaxType {}
extension Double: MinMaxType {}
extension Float: MinMaxType {}
extension Int: MinMaxType {}
extension Int8: MinMaxType {}
extension Int16: MinMaxType {}
extension Int32: MinMaxType {}
extension Int64: MinMaxType {}
extension Date: MinMaxType {}
extension NSDate: MinMaxType {}
// MARK: AddableType
/**
Types of properties which can be used with the sum and average value APIs.
- see: `sum(ofProperty:)`, `average(ofProperty:)`
*/
public protocol AddableType {
/// :nodoc:
init()
}
extension NSNumber: AddableType {}
extension Double: AddableType {}
extension Float: AddableType {}
extension Int: AddableType {}
extension Int8: AddableType {}
extension Int16: AddableType {}
extension Int32: AddableType {}
extension Int64: AddableType {}
/**
`Results` is an auto-updating container type in Realm returned from object queries.
`Results` can be queried with the same predicates as `List<Element>`, and you can
chain queries to further filter query results.
`Results` always reflect the current state of the Realm on the current thread, including during write transactions on
the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over
the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be
excluded by the filter during the enumeration.
`Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is
requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any
unnecessary work processing the intermediate state.
Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date,
with the work done to keep them up-to-date done on a background thread whenever possible.
Results instances cannot be directly instantiated.
*/
public final class Results<Element: RealmCollectionValue>: NSObject, NSFastEnumeration {
internal let rlmResults: RLMResults<AnyObject>
/// A human-readable description of the objects represented by the results.
public override var description: String {
return RLMDescriptionWithMaxDepth("Results", rlmResults, RLMDescriptionMaxDepth)
}
// MARK: Fast Enumeration
/// :nodoc:
public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>,
objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>,
count len: Int) -> Int {
return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len)))
}
/// The type of the objects described by the results.
public typealias ElementType = Element
// MARK: Properties
/// The Realm which manages this results. Note that this property will never return `nil`.
public var realm: Realm? { return Realm(rlmResults.realm) }
/**
Indicates if the results are no longer valid.
The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be
accessed, but will always be empty.
*/
public var isInvalidated: Bool { return rlmResults.isInvalidated }
/// The number of objects in the results.
public var count: Int { return Int(rlmResults.count) }
// MARK: Initializers
internal init(_ rlmResults: RLMResults<AnyObject>) {
self.rlmResults = rlmResults
}
// MARK: Index Retrieval
/**
Returns the index of the given object in the results, or `nil` if the object is not present.
*/
public func index(of object: Element) -> Int? {
return notFoundToNil(index: rlmResults.index(of: object as AnyObject))
}
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: predicate))
}
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat,
argumentArray: unwrapOptionals(in: args))))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(position: Int) -> Element {
throwForNegativeIndex(position)
return dynamicBridgeCast(fromObjectiveC: rlmResults.object(at: UInt(position)))
}
/// Returns the first object in the results, or `nil` if the results are empty.
public var first: Element? { return rlmResults.firstObject().map(dynamicBridgeCast) }
/// Returns the last object in the results, or `nil` if the results are empty.
public var last: Element? { return rlmResults.lastObject().map(dynamicBridgeCast) }
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results.
- parameter key: The name of the property whose values are desired.
*/
public override func value(forKey key: String) -> Any? {
return value(forKeyPath: key)
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results.
- parameter keyPath: The key path to the property whose values are desired.
*/
public override func value(forKeyPath keyPath: String) -> Any? {
return rlmResults.value(forKeyPath: keyPath)
}
/**
Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and
`key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
public override func setValue(_ value: Any?, forKey key: String) {
return rlmResults.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return Results<Element>(rlmResults.objects(with: NSPredicate(format: predicateFormat,
argumentArray: unwrapOptionals(in: args))))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> {
return Results<Element>(rlmResults.objects(with: predicate))
}
// MARK: Sorting
/**
Returns a `Results` containing the objects represented by the results, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing the objects represented by the results, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return Results<Element>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
/**
Returns a `Results` containing distinct objects based on the specified key paths
- parameter keyPaths: The key paths used produce distinct results
*/
public func distinct<S: Sequence>(by keyPaths: S) -> Results<Element>
where S.Iterator.Element == String {
return Results<Element>(rlmResults.distinctResults(usingKeyPaths: Array(keyPaths)))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmResults.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmResults.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the results.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T {
return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the results, or `nil` if the results are empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<T: AddableType>(ofProperty property: String) -> T? {
return rlmResults.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken {
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
}
}
}
extension Results: RealmCollection {
// MARK: Sequence Support
/// Returns a `RLMIterator` that yields successive elements in the results.
public func makeIterator() -> RLMIterator<Element> {
return RLMIterator(collection: rlmResults)
}
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// :nodoc:
public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) ->
NotificationToken {
let anyCollection = AnyRealmCollection(self)
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
}
}
}
// MARK: AssistedObjectiveCBridgeable
extension Results: AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results {
return Results(objectiveCValue as! RLMResults)
}
var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: rlmResults, metadata: nil)
}
}
|
mit
|
959330402fa7bdc9e3364da5aae85b56
| 39.035714 | 122 | 0.685519 | 4.948499 | false | false | false | false |
mgsergio/omim
|
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewStatus/BaseRoutePreviewStatus.swift
|
2
|
7552
|
@objc(MWMBaseRoutePreviewStatus)
final class BaseRoutePreviewStatus: SolidTouchView {
@IBOutlet private weak var errorBox: UIView!
@IBOutlet private weak var resultsBox: UIView!
@IBOutlet private weak var heightBox: UIView!
@IBOutlet private weak var manageRouteBox: UIView! {
didSet {
iPhoneSpecific {
manageRouteBox.backgroundColor = UIColor.blackOpaque()
}
}
}
@IBOutlet private weak var taxiBox: UIView!
@IBOutlet private weak var errorLabel: UILabel!
@IBOutlet private weak var resultLabel: UILabel!
@IBOutlet private weak var arriveLabel: UILabel?
@IBOutlet private weak var heightProfileImage: UIImageView!
@IBOutlet private weak var heightProfileElevationHeight: UILabel?
@IBOutlet private weak var manageRouteButtonRegular: UIButton! {
didSet {
configManageRouteButton(manageRouteButtonRegular)
}
}
@IBOutlet private weak var manageRouteButtonCompact: UIButton? {
didSet {
configManageRouteButton(manageRouteButtonCompact!)
}
}
@IBOutlet private var errorBoxBottom: NSLayoutConstraint!
@IBOutlet private var resultsBoxBottom: NSLayoutConstraint!
@IBOutlet private var heightBoxBottom: NSLayoutConstraint!
@IBOutlet private var taxiBoxBottom: NSLayoutConstraint!
@IBOutlet private var manageRouteBoxBottom: NSLayoutConstraint!
@IBOutlet private var heightBoxBottomManageRouteBoxTop: NSLayoutConstraint!
private var hiddenConstraint: NSLayoutConstraint!
@objc weak var ownerView: UIView!
weak var navigationInfo: MWMNavigationDashboardEntity?
var elevation: NSAttributedString? {
didSet {
guard let elevation = elevation else { return }
alternative(iPhone: { self.updateResultsLabel() },
iPad: { self.heightProfileElevationHeight?.attributedText = elevation })()
}
}
private var isVisible = false {
didSet {
alternative(iPhone: {
guard self.isVisible != oldValue else { return }
if self.isVisible {
self.addView()
}
DispatchQueue.main.async {
guard let sv = self.superview else { return }
sv.setNeedsLayout()
self.hiddenConstraint.isActive = !self.isVisible
UIView.animate(withDuration: kDefaultAnimationDuration,
animations: { sv.layoutIfNeeded() },
completion: { _ in
if !self.isVisible {
self.removeFromSuperview()
}
})
}
},
iPad: { self.isHidden = !self.isVisible })()
}
}
private func addView() {
guard superview != ownerView else { return }
ownerView.addSubview(self)
NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: ownerView, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: ownerView, attribute: .right, multiplier: 1, constant: 0).isActive = true
hiddenConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: ownerView, attribute: .bottom, multiplier: 1, constant: 0)
hiddenConstraint.priority = UILayoutPriority.defaultHigh
hiddenConstraint.isActive = true
let visibleConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: ownerView, attribute: .bottom, multiplier: 1, constant: 0)
visibleConstraint.priority = UILayoutPriority.defaultLow
visibleConstraint.isActive = true
}
private func updateHeight() {
DispatchQueue.main.async {
self.setNeedsLayout()
self.errorBoxBottom.isActive = !self.errorBox.isHidden
self.resultsBoxBottom.isActive = !self.resultsBox.isHidden
self.heightBoxBottom.isActive = !self.heightBox.isHidden
self.heightBoxBottomManageRouteBoxTop.isActive = !self.heightBox.isHidden
self.taxiBoxBottom.isActive = !self.taxiBox.isHidden
self.manageRouteBoxBottom.isActive = !self.manageRouteBox.isHidden
UIView.animate(withDuration: kDefaultAnimationDuration) { self.layoutIfNeeded() }
}
}
private func configManageRouteButton(_ button: UIButton) {
button.titleLabel?.font = UIFont.medium14()
button.setTitle(L("planning_route_manage_route"), for: .normal)
button.tintColor = UIColor.blackSecondaryText()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateManageRouteVisibility()
updateHeight()
}
private func updateManageRouteVisibility() {
let isCompact = traitCollection.verticalSizeClass == .compact
manageRouteBox.isHidden = isCompact || resultsBox.isHidden
manageRouteButtonCompact?.isHidden = !isCompact
}
@objc func hide() {
isVisible = false
}
@objc func showError(message: String) {
isVisible = true
errorBox.isHidden = false
resultsBox.isHidden = true
heightBox.isHidden = true
taxiBox.isHidden = true
manageRouteBox.isHidden = true
errorLabel.text = message
updateHeight()
}
@objc func showReady() {
isVisible = true
errorBox.isHidden = true
if MWMRouter.isTaxi() {
taxiBox.isHidden = false
resultsBox.isHidden = true
heightBox.isHidden = true
} else {
taxiBox.isHidden = true
resultsBox.isHidden = false
self.elevation = nil
if MWMRouter.hasRouteAltitude() {
heightBox.isHidden = false
MWMRouter.routeAltitudeImage(for: heightProfileImage.frame.size,
completion: { image, elevation in
self.heightProfileImage.image = image
if let elevation = elevation {
let attributes: [NSAttributedStringKey: Any] =
[
NSAttributedStringKey.foregroundColor: UIColor.linkBlue(),
NSAttributedStringKey.font: UIFont.medium14(),
]
self.elevation = NSAttributedString(string: "▲▼ \(elevation)", attributes: attributes)
}
})
} else {
heightBox.isHidden = true
}
}
updateManageRouteVisibility()
updateHeight()
}
private func updateResultsLabel() {
guard let info = navigationInfo else { return }
resultLabel.attributedText = alternative(iPhone: {
let result = info.estimate.mutableCopy() as! NSMutableAttributedString
if let elevation = self.elevation {
result.append(info.estimateDot)
result.append(elevation)
}
return result.copy() as? NSAttributedString
},
iPad: { info.estimate })()
}
@objc func onNavigationInfoUpdated(_ info: MWMNavigationDashboardEntity) {
navigationInfo = info
updateResultsLabel()
arriveLabel?.text = String(coreFormat: L("routing_arrive"), arguments: [info.arrival])
}
override var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections {
return alternative(iPhone: .bottom, iPad: [])
}
override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections {
return alternative(iPhone: .bottom, iPad: [])
}
override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections {
return alternative(iPhone: .bottom, iPad: [])
}
}
|
apache-2.0
|
bca541e5ecfcdc8e9b3081e71ba64096
| 35.819512 | 164 | 0.667859 | 5.028648 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Requests/Comment/CommentsRequest.swift
|
1
|
2960
|
//
// CommentsRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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
public class CommentsRequest: Request {
public override var method: RequestMethod { return .get }
public override var parameters: Dictionary<String, AnyObject> { return prepareParametersDictionary() }
public override var endpoint: String {
if let creationId = creationId {
return "creations/\(creationId)/comments"
}
if let galleryId = galleryId {
return "galleries/\(galleryId)/comments"
}
if let userId = userId {
return "users/\(userId)/comments"
}
return ""
}
fileprivate var creationId: String?
fileprivate var galleryId: String?
fileprivate var userId: String?
fileprivate let page: Int?
fileprivate let perPage: Int?
public init(creationId: String, page: Int?, perPage: Int?) {
self.creationId = creationId
self.page = page
self.perPage = perPage
self.galleryId = nil
self.userId = nil
}
public init(galleryId: String, page: Int?, perPage: Int?) {
self.creationId = nil
self.page = page
self.perPage = perPage
self.galleryId = galleryId
self.userId = nil
}
public init(userId: String, page: Int?, perPage: Int?) {
self.creationId = nil
self.page = page
self.perPage = perPage
self.galleryId = nil
self.userId = userId
}
func prepareParametersDictionary() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
if let page = page {
params["page"] = page as AnyObject?
}
if let perPage = perPage {
params["per_page"] = perPage as AnyObject?
}
return params
}
}
|
mit
|
6877231b3a98c63a33ab96780d85344f
| 33.418605 | 106 | 0.659122 | 4.519084 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
Classes/Swift/VFSUtil.swift
|
1
|
8980
|
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* 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 UIKit
import Foundation
import Security
import CommonCrypto
import linphonesw
import os
@objc class VFSUtil: NSObject {
@objc static let keyChainSharingGroup = "org.linphone.phone" // Enable Keychain Sharing capabilities in app and all app extensions that need to activate VFS and set key chain group to be the bundle ID for all and here
@objc static let TEAM_ID = "Z2V957B3D6" // Apple TEAM ID
@objc static let keyName = "\(keyChainSharingGroup).vfskey"
@objc static let prefName = "\(keyChainSharingGroup).vfspref"
@objc static let accessGroup = "\(TEAM_ID).\(keyChainSharingGroup)"
@objc static func generateKey(requiresBiometry: Bool = false) throws {
let flags: SecAccessControlCreateFlags
if #available(iOS 11.3, *) {
flags = requiresBiometry ?
[.privateKeyUsage, .biometryCurrentSet] : .privateKeyUsage
} else {
flags = requiresBiometry ?
[.privateKeyUsage, .touchIDCurrentSet] : .privateKeyUsage
}
let access =
SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleAlwaysThisDeviceOnly,flags,nil)!
let tag = keyName.data(using: .utf8)!
let attributes: [String: Any] = [
kSecAttrKeyType as String : kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits as String : 256,
kSecAttrTokenID as String : kSecAttrTokenIDSecureEnclave,
kSecPrivateKeyAttrs as String : [
kSecAttrIsPermanent as String : true,
kSecAttrApplicationTag as String : tag,
kSecAttrAccessControl as String : access
],
kSecAttrAccessGroup as String : accessGroup
]
var error: Unmanaged<CFError>?
guard let _ = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
}
@objc static func loadKey(name: String) -> SecKey? {
let tag = name.data(using: .utf8)!
let query: [String: Any] = [
kSecClass as String : kSecClassKey,
kSecAttrApplicationTag as String : tag,
kSecAttrKeyType as String : kSecAttrKeyTypeEC,
kSecReturnRef as String : true,
kSecAttrAccessGroup as String : accessGroup
]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
guard status == errSecSuccess else {
return nil
}
return (item as! SecKey)
}
@objc static func encrypt(clearText: String) -> String? {
let algorithm: SecKeyAlgorithm = .eciesEncryptionCofactorX963SHA512AESGCM
guard let privateKey = loadKey(name: keyName), let publicKey = SecKeyCopyPublicKey(privateKey), SecKeyIsAlgorithmSupported(publicKey, .encrypt, algorithm) else {
return nil
}
var error: Unmanaged<CFError>?
let clearTextData = clearText.data(using: .utf8)!
guard let encryptedData = SecKeyCreateEncryptedData(publicKey, algorithm,clearTextData as CFData, &error) as Data? else {
return nil
}
return encryptedData.base64EncodedString()
}
@objc static func decrypt(encryptedText: String) -> String? {
let algorithm: SecKeyAlgorithm = .eciesEncryptionCofactorX963SHA512AESGCM
guard let key = loadKey(name: keyName), SecKeyIsAlgorithmSupported(key, .decrypt, algorithm) else {
return nil
}
var error: Unmanaged<CFError>?
guard let clearTextData = SecKeyCreateDecryptedData(key,algorithm,Data(base64Encoded: encryptedText)! as CFData,&error) as Data? else {
print("[VFS] failed deciphering data \(String(describing: error))")
return nil
}
return String(decoding: clearTextData, as: UTF8.self)
}
@objc static func addSecuredPreference(key:String, value:String) -> Bool {
let delQuery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key.data(using: .utf8)!,
kSecAttrAccessGroup as String : accessGroup]
SecItemDelete(delQuery as CFDictionary)
let insertQUery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccessGroup as String : accessGroup,
kSecAttrAccessible as String : kSecAttrAccessibleAlwaysThisDeviceOnly,
kSecAttrService as String: Bundle.main.bundleIdentifier!,
kSecAttrAccount as String: key.data(using: .utf8)!,
kSecValueData as String:value.data(using: .utf8)!]
let insertStatus = SecItemAdd(insertQUery as CFDictionary, nil)
log("[VFS] addSecuredPreference : SecItemAdd status \(insertStatus)", .info)
return insertStatus == errSecSuccess
}
@objc static func deleteSecurePreference(key:String) {
let delQuery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key.data(using: .utf8)!,
kSecAttrAccessGroup as String : accessGroup]
let deleteSatus = SecItemDelete(delQuery as CFDictionary)
log("[VFS] deleteSecurePreference : SecItemDelete status for removing key \(key) = \(deleteSatus)", .info)
}
@objc static func getSecuredPreference(key:String) -> String? {
let query: [String:Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key.data(using: .utf8)!,
kSecReturnData as String: kCFBooleanTrue,
kSecAttrAccessGroup as String : accessGroup,
]
var result: AnyObject?
let status: OSStatus = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
log("[VFS] getSecuredPreference : SecItemCopyMatching status \(status)", .info)
return status == errSecSuccess ? String(decoding: result as! Data , as: UTF8.self) : nil
}
@objc static func randomSha512() -> String {
let data = UUID.init().uuidString.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
data.withUnsafeBytes({
_ = CC_SHA512($0, CC_LONG(data.count), &digest)
})
return digest.map({ String(format: "%02hhx", $0) }).joined(separator: "")
}
@objc static func activateVFS(forFirstTime: Bool = false) -> Bool {
do {
if (forFirstTime) {
removeExistingVFSKeyIfAny()
}
if (getSecuredPreference(key: prefName) == nil) {
log("[VFS] no secret key set, building one.", .info)
try generateKey(requiresBiometry: false)
guard let encryptedHash = encrypt(clearText: randomSha512()) else {
return false
}
if (!addSecuredPreference(key: prefName, value: encryptedHash)) {
log("[VFS] Unable to save encrypted key in secured defaults.", .error)
}
}
guard let encryptedKey = getSecuredPreference(key: prefName) else {
log("[VFS] Unable to retrieve encrypted key.", .error)
return false
}
guard let secret = decrypt(encryptedText: encryptedKey) else {
log("[VFS] Unable to decryt encrypted key.", .error)
removeExistingVFSKeyIfAny()
return false
}
Factory.Instance.setVfsEncryption(encryptionModule: 2, secret: secret, secretSize: 32)
log("[VFS] activated", .info)
return true
} catch {
log("[VFS] Error setting up VFS: \(error)", .info)
return false
}
}
@objc static func vfsEnabled(groupName: String) -> Bool {
let defaults = UserDefaults.init(suiteName: groupName)
if (defaults == nil) {
log("[VFS] Unable to get VFS enabled preference userDefaults is null",.error);
}
return defaults?.bool(forKey: "vfs_enabled_preference") == true
}
@objc static func setVfsEnabbled(enabled: Bool, groupName: String) {
let defaults = UserDefaults.init(suiteName: groupName)
if (defaults == nil) {
log("[VFS] Unable to set VFS enabled preferece userDefaults is null",.error);
}
defaults?.setValue(enabled, forKey: "vfs_enabled_preference")
}
@objc static func log(_ log:String, _ level: OSLogType) {
switch (level) {
case.info:LoggingService.Instance.message(message: log)
case.debug:LoggingService.Instance.debug(message: log)
case.error:LoggingService.Instance.error(message: log)
case.fault:LoggingService.Instance.fatal(message: log)
default:LoggingService.Instance.message(message: log)
}
if #available(iOS 10.0, *) {
os_log("%{public}@", type: level,log)
} else {
NSLog(log)
}
}
@objc static func removeExistingVFSKeyIfAny() {
log("[VFS] removing existing key if any",.debug)
if (getSecuredPreference(key: prefName) != nil) {
deleteSecurePreference(key: prefName)
}
}
}
|
gpl-3.0
|
fa3b9144f3d6e2a3026627bc9192dbfe
| 35.954733 | 218 | 0.715145 | 3.822903 | false | false | false | false |
space150/spaceLock
|
ios/spacelab/SLLockListViewController.swift
|
3
|
9098
|
//
// SLLockListViewController.swift
// spacelab
//
// Created by Shawn Roske on 3/20/15.
// Copyright (c) 2015 space150, Inc.
//
// 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 LockKit
import AudioToolbox
class SLLockViewController: UIViewController,
UITableViewDelegate,
UITableViewDataSource,
NSFetchedResultsControllerDelegate,
SLLockViewCellDelegate
{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var logoutButton: UIButton!
@IBOutlet weak var noResultsView: UIView!
private var fetchedResultsController: NSFetchedResultsController!
private var discoveryManager: LKLockDiscoveryManager!
private var unlocking:Bool!
private var security: LKSecurityManager!
override func viewDidLoad()
{
super.viewDidLoad()
discoveryManager = LKLockDiscoveryManager(context: "ios-client")
unlocking = false
security = LKSecurityManager()
fetchedResultsController = getFetchedResultsController()
fetchedResultsController.delegate = self
fetchedResultsController.performFetch(nil)
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
discoveryManager.startDiscovery()
}
override func viewWillDisappear(animated: Bool)
{
super.viewWillDisappear(animated)
discoveryManager.stopDiscovery()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDataSource Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return fetchedResultsController.sections!.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return fetchedResultsController.sections![section].numberOfObjects
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:SLLockViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! SLLockViewCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: SLLockViewCell, atIndexPath indexPath: NSIndexPath)
{
let lock: LKLock = fetchedResultsController.objectAtIndexPath(indexPath) as! LKLock
cell.delegate = self
cell.setLock(lock, indexPath: indexPath)
}
// MARK: - NSFetchedResultsController methods
func getFetchedResultsController() -> NSFetchedResultsController
{
let fetchedResultsController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: LKLockRepository.sharedInstance().managedObjectContext!!,
sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}
func taskFetchRequest() -> NSFetchRequest
{
let fetchRequest = NSFetchRequest(entityName: "LKLock")
let sortDescriptor = NSSortDescriptor(key: "proximity", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
func controllerWillChangeContent(controller: NSFetchedResultsController)
{
if ( !unlocking )
{
self.tableView.beginUpdates()
}
}
func controller(controller: NSFetchedResultsController, didChangeObject object: AnyObject, atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
{
if ( !unlocking )
{
switch type
{
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Update:
if ( self.tableView.cellForRowAtIndexPath(indexPath!) != nil )
{
let cell: SLLockViewCell = self.tableView.cellForRowAtIndexPath(indexPath!) as! SLLockViewCell
self.configureCell(cell, atIndexPath: indexPath!)
self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
}
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
default:
return
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController)
{
if ( !unlocking )
{
self.tableView.endUpdates()
noResultsView.hidden = ( fetchedResultsController.fetchedObjects?.count > 0 )
}
}
// MARK: - UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
performUnlock(indexPath)
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
{
let lock: LKLock = fetchedResultsController.objectAtIndexPath(indexPath) as! LKLock
if ( lock.proximity.integerValue == 2 || lock.proximity.integerValue == 3 )
{
return indexPath
}
return nil
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let lock: LKLock = fetchedResultsController.objectAtIndexPath(indexPath) as! LKLock
if ( lock.proximity.integerValue == 2 || lock.proximity.integerValue == 3 )
{
return true
}
return false
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == UITableViewCellEditingStyle.Delete
{
// remove coredata entry
let lock: LKLock = fetchedResultsController.objectAtIndexPath(indexPath) as! LKLock
LKLockRepository.sharedInstance().managedObjectContext!!.deleteObject(lock)
LKLockRepository.sharedInstance().saveContext()
}
}
func performUnlock(indexPath: NSIndexPath)
{
unlocking = true
let lock: LKLock = fetchedResultsController.objectAtIndexPath(indexPath) as! LKLock
let cell: SLLockViewCell = self.tableView.cellForRowAtIndexPath(indexPath) as! SLLockViewCell
cell.showInProgress()
// fetch the key from the keychain
var keyData = security.findKey(lock.lockId)
if keyData != nil
{
self.discoveryManager.openLock(lock, withKey:keyData, complete: { (success, error) -> Void in
if ( success )
{
dispatch_async(dispatch_get_main_queue(), {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
cell.showUnlocked()
})
}
else
{
println("ERROR opening lock: \(error.localizedDescription)")
dispatch_async(dispatch_get_main_queue(), {
cell.resetUnlocked()
})
}
})
}
else
{
println("error: unable to find key")
dispatch_async(dispatch_get_main_queue(), {
cell.resetUnlocked()
})
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - SLLockViewCellDelegate Methods
func lockCompleted()
{
self.unlocking = false
tableView.reloadData()
}
}
|
mit
|
09f1671217772f4b84dce31a9d088e46
| 34.542969 | 179 | 0.645087 | 5.780178 | false | false | false | false |
dbahat/conventions-ios
|
Conventions/Conventions/model/Update.swift
|
1
|
1086
|
//
// Update.swift
// Conventions
//
// Created by David Bahat on 3/4/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
class Update {
var id: String = "";
var text: String = "";
var date: Date = Date.now();
var isNew = true;
init(id: String, text: String, date: Date) {
self.id = id;
self.text = text;
self.date = date;
}
init?(json: Dictionary<String, AnyObject>) {
guard let id = json["id"] as? String else {return nil}
guard let text = json["text"] as? String else {return nil}
guard let date = json["date"] as? TimeInterval else {return nil}
guard let isNew = json["isNew"] as? Bool else {return nil}
self.id = id;
self.text = text;
self.date = Date(timeIntervalSince1970: date);
self.isNew = isNew;
}
func toJson() -> Dictionary<String, AnyObject> {
return ["id": id as AnyObject, "text": text as AnyObject, "date": date.timeIntervalSince1970 as AnyObject, "isNew": isNew as AnyObject];
}
}
|
apache-2.0
|
7bed00c5328a9fd6bb08c687e5079077
| 27.552632 | 144 | 0.580645 | 3.767361 | false | false | false | false |
ivlasov/EvoShare
|
Pods/Starscream/WebSocket.swift
|
2
|
30213
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : Array<String>?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 2048
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var isCreated = false
private var writeQueue: NSOperationQueue?
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
private var connectedBlock: ((Void) -> Void)? = nil
private var disconnectedBlock: ((NSError?) -> Void)? = nil
private var receivedTextBlock: ((String) -> Void)? = nil
private var receivedDataBlock: ((NSData) -> Void)? = nil
public var isConnected :Bool {
return connected
}
//init the websocket with a url
public init(url: NSURL) {
self.url = url
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
//closure based instead of the delegate
public convenience init(url: NSURL, protocols: Array<String>, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void), data:(NSData) -> Void) {
self.init(url: url, protocols: protocols)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
receivedDataBlock = data
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), data:((NSData) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedDataBlock = data
}
///Connect to the websocket server on a background thread
public func connect() {
if isCreated {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
self.isCreated = true
self.createHTTPRequest()
self.isCreated = false
})
}
///disconnect from the websocket server
public func disconnect() {
writeError(CloseCode.Normal.rawValue)
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let str: NSString = url.absoluteString!
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1)
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
}
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
self.addHeader(urlRequest, key: key, val: value)
}
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
self.initStreamsWithData(serializedRequest, Int(port!))
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest.takeUnretainedValue(),
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
}
if self.voipEnabled {
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if writeQueue != nil {
writeQueue!.waitUntilAllOperationsAreFinished()
}
if let stream = inputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
if let stream = outputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
outputStream = nil
isRunLoop = false
connected = false
dispatch_async(queue,{
if let disconnectBlock = self.disconnectedBlock {
disconnectBlock(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
connected = processHTTP(buffer, bufferLen: length)
if !connected {
dispatch_async(queue,{
//self.workaroundMethod()
let error = self.errorWithDetail("Invalid HTTP upgrade", code: 1)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
} else {
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if (fragBuffer != nil) {
var combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{
//self.workaroundMethod()
if let connectBlock = self.connectedBlock {
connectBlock()
}
self.delegate?.websocketDidConnect(self)
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
CFHTTPMessageAppendBytes(response.takeUnretainedValue(), buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response.takeUnretainedValue()) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
var response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
var offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].bigEndian
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = UnsafePointer<UInt8>((buffer+offset))
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
let error = self.errorWithDetail("connection closed by server", code: code)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].bigEndian
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].bigEndian)
offset += sizeof(UInt16)
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("first frame can't be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{
if let textBlock = self.receivedTextBlock{
textBlock(str! as! String)
}
self.delegate?.websocketDidReceiveMessage(self, text: str! as! String)
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{
//self.workaroundMethod()
if let dataBlock = self.receivedDataBlock{
dataBlock(data)
}
self.delegate?.websocketDidReceiveData(self, data: data)
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.bigEndian
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream in a
private func dequeueWrite(data: NSData, code: OpCode) {
if writeQueue == nil {
writeQueue = NSOperationQueue()
writeQueue!.maxConcurrentOperationCount = 1
}
writeQueue!.addOperationWithBlock {
//stream isn't ready, let's wait
var tries = 0;
while self.outputStream == nil || !self.connected {
if(tries < 5) {
sleep(1);
} else {
break;
}
tries++;
}
if !self.connected {
return
}
var offset = 2
UINT16_MAX
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = self.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).bigEndian
offset += sizeof(UInt16)
} else {
buffer[1] = 127
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).bigEndian
offset += sizeof(UInt64)
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if self.outputStream == nil {
break
}
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
if len == nil || len! < 0 {
var error: NSError?
if let streamError = self.outputStream?.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = self.errorWithDetail("output stream error during write", code: errCode)
}
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
break
} else {
total += len!
}
if total >= offset {
break
}
}
}
}
}
|
unlicense
|
fee75b8cef3ffefaa417ddf018ec4099
| 40.788382 | 174 | 0.553305 | 5.482308 | false | false | false | false |
webim/webim-client-sdk-ios
|
WebimClientLibrary/Implementation/UploadedFileImpl.swift
|
1
|
3594
|
//
// UploadedFileImpl.swift
// WebimClientLibrary
//
// Created by Nikita Kaberov on 15.11.20.
// Copyright © 2020 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
Internal uploaded file representasion.
- author:
Nikita Kaberov
- copyright:
2020 Webim
*/
class UploadedFileImpl {
// MARK: - Properties
private let size: Int64
private let guid: String
private let contentType: String?
private let filename: String
private let visitorID: String
private let clientContentType: String
private let imageParameters: ImageParameters?
// MARK: - Initialization
init(size: Int64,
guid: String,
contentType: String?,
filename: String,
visitorID: String,
clientContentType: String,
imageParameters: ImageParameters?) {
self.size = size
self.guid = guid
self.contentType = contentType
self.filename = filename
self.visitorID = visitorID
self.clientContentType = clientContentType
self.imageParameters = imageParameters
}
}
extension UploadedFileImpl: UploadedFile {
public var description: String {
let imageSize = imageParameters?.getSize()
return "{\"client_content_type\":\"\(clientContentType)\"" +
",\"visitor_id\":\"\(visitorID)\"" +
",\"filename\":\"\(filename)\"" +
",\"content_type\":\"\(contentType ?? "")\"" +
",\"guid\":\"\(guid)\"" +
(imageSize != nil ? ",\"image\":{\"size\":{\"width\":\( imageSize?.getWidth() ?? 0),\"height\":\(imageSize?.getHeight() ?? 0)}}" : "") +
",\"size\":\(size)}"
}
func getSize() -> Int64 {
return size
}
func getGuid() -> String {
return guid
}
func getFileName() -> String {
return filename
}
func getContentType() -> String? {
return contentType
}
func getVisitorID() -> String {
return visitorID
}
func getClientContentType() -> String {
return clientContentType
}
func getImageInfo() -> ImageInfo? {
return ImageInfoImpl(withThumbURLString: "",
fileUrlCreator: nil,
filename: filename,
guid: guid,
width: imageParameters?.getSize()?.getWidth(),
height: imageParameters?.getSize()?.getHeight())
}
}
|
mit
|
0593cffea5db8062e1e8d13b6cfc3a69
| 31.963303 | 148 | 0.616755 | 4.809906 | false | false | false | false |
iOS-mamu/SS
|
P/Library/Eureka/Source/Rows/PopoverSelectorRow.swift
|
1
|
1484
|
//
// PopoverSelectorRow.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
open class _PopoverSelectorRow<T: Equatable, Cell: CellType> : SelectorRow<T, Cell, SelectorViewController<T>> where Cell: BaseCell, Cell: TypedCellType, Cell.Value == T {
public required init(tag: String?) {
super.init(tag: tag)
onPresentCallback = { [weak self] (_, viewController) -> Void in
guard let porpoverController = viewController.popoverPresentationController, let tableView = self?.baseCell.formViewController()?.tableView, let cell = self?.cell else {
fatalError()
}
porpoverController.sourceView = tableView
porpoverController.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell)
}
presentationMode = .popover(controllerProvider: ControllerProvider.callback { return SelectorViewController<T>(){ _ in } }, completionCallback: { [weak self] in
$0.dismiss(animated: true, completion: nil)
self?.reload()
})
}
open override func didSelect() {
deselect()
super.didSelect()
}
}
public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<T, PushSelectorCell<T>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
cce199f8f71886e61c96e4b752483d8d
| 38.026316 | 181 | 0.6588 | 4.591331 | false | false | false | false |
billyburton/SwiftMySql
|
Sources/SwiftMySql/MySqlReader.swift
|
1
|
1395
|
//
// MySqlReader.swift
// mysql_ui
//
// Created by William Burton on 01/02/2017.
// Copyright © 2017 William Burton. All rights reserved.
//
import SwiftCMySqlMac
import Foundation
class MySqlReader: MySqlReaderProtocol {
private let connection: MySqlConnectionProtocol
private var results: MySqlResultsProtocol
lazy var schema: MySqlSchemaProtocol = MySqlFactory.createSchema(results: self.results)
public var columnNames: [String] {
get {
return schema.columnNames
}
}
required init(connection: MySqlConnectionProtocol) throws {
self.connection = connection
results = try connection.storeResults()
}
func nextResultSet() throws -> Bool {
if connection.nextResult() {
results = try connection.storeResults()
return true
}
return false
}
public func next() -> Bool {
return results.getNextRow()
}
public func getString(ordinal: Int) -> String {
return results.getString(ordinal)
}
public func getString(columnName: String) throws -> String {
let ordinal = schema.getOrdinalPosition(forColumn: columnName)
if ordinal == -1 {
throw MySqlErrors.InvalidColumnSpecified
}
return getString(ordinal: ordinal)
}
}
|
apache-2.0
|
f28562dbbf4df1aa63c234e74cb0f3c2
| 23.45614 | 91 | 0.621234 | 4.725424 | false | false | false | false |
iamrajhans/RatingAppiOS
|
RatingApp/RatingApp/MealViewController.swift
|
1
|
2482
|
//
// ViewController.swift
// RatingApp
//
// Created by Rajhans Jadhao on 11/09/16.
// Copyright © 2016 Rajhans Jadhao. All rights reserved.
//
import UIKit
class MealViewController: UIViewController , UITextFieldDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate{
@IBOutlet weak var mealNameTextField: UITextField!
@IBOutlet weak var mealImageView: UIImageView!
var meal :Meal?
@IBOutlet weak var saveButton: UIBarButtonItem!
override func viewDidLoad() {
mealNameTextField.delegate = self
if let meal = meal {
navigationItem.title = meal.name
mealNameTextField.text = meal.name
mealImageView.image = meal.photo
}
}
// Actions
@IBAction func selectImageFromPhotolibrary(sender: UITapGestureRecognizer) {
let imagePicker = UIImagePickerController ()
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
mealImageView.image = selectedImage
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func selectPicFromphotolib(sender: UIButton) {
let imagePicker = UIImagePickerController ()
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = mealNameTextField.text ?? ""
let photo = mealImageView.image
meal = Meal(name: name, photo: photo, rating: 3)
}
}
@IBAction func cancel(sender: UIBarButtonItem) {
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismissViewControllerAnimated(true, completion: nil)
}
else {
navigationController!.popViewControllerAnimated(true)
}
}
}
|
mit
|
3747563d81cb66a37d3467b8a39c771f
| 29.62963 | 157 | 0.650544 | 5.893112 | false | false | false | false |
gobetti/Swift
|
BasicAgenda/BasicAgenda/TableListViewController.swift
|
1
|
3870
|
//
// TableListViewcontroller.swift
// BasicAgenda
//
// Created by Carlos Butron on 12/04/15.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
import UIKit
class TableListViewController: UITableViewController, NewContactDelegate {
var contactArray = Array<Contact>()
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...50 {
let contact = Contact()
contact.name = "Name\(i)"
contact.surname = "Surname\(i)"
contact.phone = "Phone\(i)"
contact.email = "Email\(i)"
contactArray.append(contact)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contactArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let contact = contactArray[indexPath.row]
cell.textLabel!.text = contact.name + " " + contact.surname
cell.tag = indexPath.row
print("Cell number: \(indexPath.row)")
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goToDetailFromListado" {
let detailViewController = segue.destinationViewController as! DetailViewController
let cell = sender as! UITableViewCell
detailViewController.contact = contactArray[cell.tag]
} else if segue.identifier == "goToNewContactFromListado" {
let navigationController = segue.destinationViewController as! UINavigationController
let newContactViewController = navigationController.viewControllers[0] as! NewContactViewController
newContactViewController.delegate = self
}
}
// MARK: - Delegate
func newContact(contact: Contact) {
contactArray.append(contact)
tableView.reloadData()
}
}
|
mit
|
c38f248b69f81bcf584ac55dcbd259ae
| 30.721311 | 157 | 0.64522 | 5.481586 | false | false | false | false |
twocentstudios/todostream
|
todostream/TodoDetailViewController.swift
|
1
|
7183
|
//
// Created by Christopher Trott on 12/5/15.
// Copyright © 2015 twocentstudios. All rights reserved.
//
import UIKit
import ReactiveCocoa
import Result
final class TodoDetailViewController: UITableViewController {
let appContext: AppContext
var viewModel: TodoDetailViewModel
init(viewModel: TodoDetailViewModel, appContext: AppContext) {
self.viewModel = viewModel
self.appContext = appContext
super.init(style: .Grouped)
self.title = "Update Item"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "doCancel")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .Plain, target: self, action: "doSave")
tableView.registerClass(TodoDetailCell.self, forCellReuseIdentifier: TodoDetailCell.reuseIdentifier)
tableView.rowHeight = 50
tableView.delegate = self
tableView.dataSource = self
appContext.eventsSignal
.takeUntilNil { [weak self] in self }
.map { event -> Result<TodoDetailViewModel, NSError>? in if case let .ResponseUpdateDetailViewModel(result) = event { return result }; return nil }
.ignoreNil()
.map { $0.error }
.ignoreNil()
.observeOn(UIScheduler())
.observeNext { [unowned self] error in
self.presentError(error)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func doCancel() {
appContext.eventsObserver.sendNext(Event.ResponseUpdateDetailViewModel(Result(value: viewModel)))
}
func doSave() {
appContext.eventsObserver.sendNext(Event.RequestUpdateDetailViewModel(viewModel))
}
func presentError(error: NSError) {
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return viewModel.propertyCount
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TodoDetailCell.reuseIdentifier, forIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return "Title"
case 1: return "Subtitle"
case 2: return "Priority"
case 3: return nil
case 4: return nil
default: return nil
}
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.textLabel?.text = nil
cell.textLabel?.textColor = UIColor.blackColor()
cell.detailTextLabel?.text = nil
cell.detailTextLabel?.textColor = cell.tintColor
switch indexPath.section {
case 0:
cell.textLabel?.text = viewModel.title
cell.detailTextLabel?.text = "edit"
case 1:
cell.textLabel?.text = viewModel.subtitle
cell.detailTextLabel?.text = "edit"
case 2:
cell.textLabel?.text = viewModel.priorityString
cell.detailTextLabel?.text = "toggle"
case 3:
cell.textLabel?.text = viewModel.completedString
cell.detailTextLabel?.text = "toggle"
case 4:
cell.textLabel?.text = viewModel.deletedString
cell.textLabel?.textColor = UIColor.redColor()
cell.detailTextLabel?.text = "toggle"
default:
break
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 0:
let alertController = UIAlertController(title: "Update title", message: nil, preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { [unowned self] in $0.text = self.viewModel.title }
alertController.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.Default) { [unowned self] _ in
if let newText = alertController.textFields?.first?.text { self.viewModel.title = newText }
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
})
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
case 1:
let alertController = UIAlertController(title: "Update subtitle", message: nil, preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { [unowned self] in $0.text = self.viewModel.subtitle }
alertController.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.Default) { [unowned self] _ in
if let newText = alertController.textFields?.first?.text { self.viewModel.subtitle = newText }
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
})
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
case 2:
viewModel.togglePriority()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
case 3:
viewModel.toggleCompleted()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
case 4:
viewModel.toggleDeleted()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
default: break
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
final class TodoDetailCell: UITableViewCell {
static let reuseIdentifier = "TodoDetailCell"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value1, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
b08d02bec0d4631f4b9d34a299a91bc1
| 41.005848 | 159 | 0.665274 | 5.486631 | false | false | false | false |
bi3mer/WorkSpace
|
Swift/class/class/main.swift
|
1
|
910
|
//
// main.swift
// class
//
// Created by colan biemer on 4/2/15.
// Copyright (c) 2015 colan biemer. All rights reserved.
//
// basic inheritance
import Foundation
class Shape
{
// Inital values
var numSides = 0
// Constructors
init()
{
}
init(num:Int)
{
numSides = num
}
// Description Funciton
func Description() -> String
{
return "Number of sides: \(numSides)"
}
}
class Sqaure: Shape
{
var sideLength: Int
init(numSideLength: Int)
{
sideLength = numSideLength
super.init(num: 4)
}
override func Description() -> String
{
return "All squares have 4 sides and this one has a length of \(sideLength)"
}
}
var shape = Shape()
shape.numSides = 20
println(shape.Description())
var square = Sqaure(numSideLength: 10)
println(square.Description())
|
mit
|
3f716d8155c4d4c5679e1522276edb8d
| 14.423729 | 84 | 0.584615 | 3.729508 | false | false | false | false |
divljiboy/IOSChatApp
|
Quick-Chat/Pods/BulletinBoard/Sources/Appearance/BLTNInterfaceBuilder.swift
|
1
|
7551
|
/**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* Generates interface elements for bulletins. Use this class to create custom bulletin items with
* standard components.
*/
@objc open class BLTNInterfaceBuilder: NSObject {
/// The item for which the interface builder was created.
@objc public weak var item: BLTNItem?
/// The appearance to use to generate the items.
@objc public let appearance: BLTNItemAppearance
/// Creates a new interface builder.
@objc public required init(appearance: BLTNItemAppearance, item: BLTNItem) {
self.appearance = appearance
self.item = item
}
/**
* Creates a standard title label.
*/
@objc open func makeTitleLabel() -> BLTNTitleLabelContainer {
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.textColor = appearance.titleTextColor
titleLabel.accessibilityTraits |= UIAccessibilityTraitHeader
titleLabel.numberOfLines = 2
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.font = appearance.makeTitleFont()
let needsCloseButton = item?.isDismissable == true && item?.requiresCloseButton == true
let inset: CGFloat = needsCloseButton ? 12 + 30 : 0
return BLTNTitleLabelContainer(label: titleLabel, horizontalInset: inset)
}
/**
* Creates a standard description label.
*/
@objc open func makeDescriptionLabel() -> UILabel {
let descriptionLabel = UILabel()
descriptionLabel.textAlignment = .center
descriptionLabel.textColor = appearance.descriptionTextColor
descriptionLabel.numberOfLines = 0
descriptionLabel.font = appearance.makeDescriptionFont()
return descriptionLabel
}
/**
* Creates a standard text field with an optional delegate.
*
* - parameter placeholder: The placeholder text.
* - parameter returnKey: The type of return key to apply to the text field.
* - parameter delegate: The delegate for the text field.
*/
@objc open func makeTextField(placeholder: String? = nil,
returnKey: UIReturnKeyType = .default,
delegate: UITextFieldDelegate? = nil) -> UITextField {
let textField = UITextField()
textField.delegate = delegate
textField.textAlignment = .left
textField.placeholder = placeholder
textField.borderStyle = .roundedRect
textField.returnKeyType = returnKey
return textField
}
/**
* Creates a standard action (main) button.
*
* The created button will have rounded corners, a background color set to the `tintColor` and
* a title color set to `actionButtonTitleColor`.
*
* - parameter title: The title of the button.
*/
@objc open func makeActionButton(title: String) -> BLTNHighlightButtonWrapper {
let actionButton = HighlightButton()
actionButton.cornerRadius = appearance.actionButtonCornerRadius
actionButton.setBackgroundColor(appearance.actionButtonColor, forState: .normal)
actionButton.setTitleColor(appearance.actionButtonTitleColor, for: .normal)
actionButton.contentHorizontalAlignment = .center
actionButton.setTitle(title, for: .normal)
actionButton.titleLabel?.font = appearance.makeActionButtonFont()
actionButton.clipsToBounds = true
if let color = appearance.actionButtonBorderColor {
actionButton.layer.borderColor = color.cgColor
actionButton.layer.borderWidth = appearance.actionButtonBorderWidth
}
let wrapper = BLTNHighlightButtonWrapper(button: actionButton)
wrapper.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal)
let heightConstraint = wrapper.heightAnchor.constraint(equalToConstant: 55)
heightConstraint.priority = UILayoutPriorityDefaultHigh
heightConstraint.isActive = true
return wrapper
}
/**
* Creates a standard alternative button.
*
* The created button will have no background color and a title color set to `tintColor`.
*
* - parameter title: The title of the button.
*/
@objc open func makeAlternativeButton(title: String) -> UIButton {
let alternativeButton = RoundedButton()
alternativeButton.cornerRadius = appearance.alternativeButtonCornerRadius
alternativeButton.setTitle(title, for: .normal)
alternativeButton.setTitleColor(appearance.alternativeButtonTitleColor, for: .normal)
alternativeButton.titleLabel?.font = appearance.makeAlternativeButtonFont()
if let color = appearance.alternativeButtonBorderColor {
alternativeButton.clipsToBounds = true
alternativeButton.layer.borderColor = color.cgColor
alternativeButton.layer.borderWidth = appearance.alternativeButtonBorderWidth
}
return alternativeButton
}
/**
* Creates a stack view to contain a group of objects.
*
* - parameter spacing: The spacing between elements. Defaults to `10`.
*/
@objc open func makeGroupStack(spacing: CGFloat = 10) -> UIStackView {
let buttonsStack = UIStackView()
buttonsStack.axis = .vertical
buttonsStack.alignment = .fill
buttonsStack.distribution = .fill
buttonsStack.spacing = spacing
return buttonsStack
}
/**
* Wraps a view without intrinsic content size inside a view with an intrinsic content size.
*
* This method allows you to display view without an intrinsic content size, such as collection views,
* inside stack views; by using the returned `BLTNContentView` view.
*
* - parameter view: The view to wrap in the container.
* - parameter width: The width of the content. Pass `nil` if the content has a flexible width.
* - parameter height: The height of the content. Pass `nil` if the content has a flexible height.
* - parameter position: The position of `view` inside its parent.
*
* - returns: The view that contains the `view` and an intrinsic content size. You can add the returned
* view to a stack view.
*/
@objc open func wrapView(_ view: UIView, width: NSNumber?, height: NSNumber?, position: BLTNViewPosition) -> BLTNContainerView {
let container = BLTNContainerView()
container.contentSize = CGSize(width: width.flatMap(CGFloat.init) ?? UIViewNoIntrinsicMetric,
height: height.flatMap(CGFloat.init) ?? UIViewNoIntrinsicMetric)
container.setChildView(view) { parent, child in
switch position {
case .centered:
child.centerXAnchor.constraint(equalTo: parent.centerXAnchor).isActive = true
child.centerYAnchor.constraint(equalTo: parent.centerYAnchor).isActive = true
case .pinnedToEdges:
child.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true
child.trailingAnchor.constraint(equalTo: parent.trailingAnchor).isActive = true
child.topAnchor.constraint(equalTo: parent.topAnchor).isActive = true
child.bottomAnchor.constraint(equalTo: parent.bottomAnchor).isActive = true
}
}
return container
}
}
|
mit
|
01c89236ffd431176a0edb4534aed135
| 34.450704 | 132 | 0.676864 | 5.412903 | false | false | false | false |
vigneshuvi/SwiftCSVExport
|
Examples/CarthageExport/CarthageExport/ViewController.swift
|
1
|
3093
|
//
// ViewController.swift
// CarthageExport
//
// Created by Vignesh on 08/03/17.
// Copyright © 2017 vigneshuvi. All rights reserved.
//
import UIKit
import SwiftCSVExport
class User {
var userid:Int = 0
var name:String = ""
var email:String = ""
var isValidUser:Bool = false
var message:String = ""
var balance:Double = 0.0
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Generate CSV file
let user1:NSMutableDictionary = NSMutableDictionary()
user1.setObject(107, forKey: "userid" as NSCopying);
user1.setObject("vignesh", forKey: "name" as NSCopying);
user1.setObject("[email protected]", forKey: "email" as NSCopying);
user1.setObject(true, forKey:"isValidUser" as NSCopying)
user1.setObject("Hi 'Vignesh!' \nhow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying);
user1.setObject(571.05, forKey: "balance" as NSCopying);
let user2:NSMutableDictionary = NSMutableDictionary()
user2.setObject(108, forKey: "userid" as NSCopying);
user2.setObject("vinoth", forKey: "name" as NSCopying);
user2.setObject(false, forKey:"isValidUser" as NSCopying)
user2.setObject("[email protected]", forKey: "email" as NSCopying);
user2.setObject("Hi 'Vinoth!'; \nHow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying);
user2.setObject(567.50, forKey: "balance" as NSCopying);
let data:NSMutableArray = NSMutableArray()
data.add(user1);
data.add(user2);
let user3 = User()
user3.userid = 109
user3.name = "John"
user3.email = "[email protected]"
user3.isValidUser = true
user3.message = "Hi 'John!'; \nHow are you? \t Shall we meet tomorrow? \r Thanks "
user3.balance = 105.41;
data.add(listPropertiesWithValues(user3)) // Able to convert Class object into NSMutableDictionary
let header = ["userid", "name", "email", "message", "isValidUser","balance"]
// Create a object for write CSV
let writeCSVObj = CSV()
writeCSVObj.rows = data
writeCSVObj.delimiter = DividerType.semicolon.rawValue
writeCSVObj.fields = header as NSArray
writeCSVObj.name = "userlist"
// Write File using CSV class object
let result = exportCSV(writeCSVObj);
if result.isSuccess {
guard let filePath = result.value else {
print("Export Error: \(String(describing: result.value))")
return
}
print("File Path: \(filePath)")
} else {
print("Export Error: \(String(describing: result.value))")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
0892ed0c4cd747acf14cb0867f72c84b
| 34.953488 | 126 | 0.61934 | 4.144772 | false | false | false | false |
drewcrawford/XcodeServerSDK
|
XcodeServerSDK/XcodeServerEntity.swift
|
3
|
1794
|
//
// XcodeServerEntity.swift
// Buildasaur
//
// Created by Honza Dvorsky on 14/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
public protocol XcodeRead {
init(json: NSDictionary)
}
public class XcodeServerEntity : XcodeRead {
public let id: String!
public let rev: String!
public let tinyID: String!
public let docType: String!
//when created from json, let's save the original data here.
public let originalJSON: NSDictionary?
//initializer which takes a dictionary and fills in values for recognized keys
public required init(json: NSDictionary) {
self.id = json.optionalStringForKey("_id")
self.rev = json.optionalStringForKey("_rev")
self.tinyID = json.optionalStringForKey("tinyID")
self.docType = json.optionalStringForKey("doc_type")
self.originalJSON = json.copy() as? NSDictionary
}
public init() {
self.id = nil
self.rev = nil
self.tinyID = nil
self.docType = nil
self.originalJSON = nil
}
public func dictionarify() -> NSDictionary {
assertionFailure("Must be overriden by subclasses that wish to dictionarify their data")
return NSDictionary()
}
public class func optional<T: XcodeRead>(json: NSDictionary?) -> T? {
if let json = json {
return T(json: json)
}
return nil
}
}
//parse an array of dictionaries into an array of parsed entities
public func XcodeServerArray<T where T:XcodeRead>(jsonArray: NSArray!) -> [T] {
let array = jsonArray as! [NSDictionary]!
let parsed = array.map {
(json: NSDictionary) -> (T) in
return T(json: json)
}
return parsed
}
|
mit
|
1496350142ec559b6f50ba2943922c88
| 26.181818 | 96 | 0.634337 | 4.333333 | false | false | false | false |
shorlander/firefox-ios
|
Client/Frontend/Widgets/TabsButton.swift
|
4
|
11010
|
/* 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 SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
struct TabsButtonUX {
static let TitleColor: UIColor = UIColor.black
static let TitleBackgroundColor: UIColor = UIColor.white
static let CornerRadius: CGFloat = 2
static let TitleFont: UIFont = UIConstants.DefaultChromeSmallFontBold
static let BorderStrokeWidth: CGFloat = 1
static let BorderColor: UIColor = UIColor.clear
static let TitleInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.borderColor = UIConstants.PrivateModePurple
theme.borderWidth = BorderStrokeWidth
theme.font = UIConstants.DefaultChromeBoldFont
theme.backgroundColor = UIConstants.AppBackgroundColor
theme.textColor = UIConstants.PrivateModePurple
theme.insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
theme.highlightButtonColor = UIConstants.PrivateModePurple
theme.highlightTextColor = TabsButtonUX.TitleColor
theme.highlightBorderColor = UIConstants.PrivateModePurple
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.borderColor = BorderColor
theme.borderWidth = BorderStrokeWidth
theme.font = TitleFont
theme.backgroundColor = TitleBackgroundColor
theme.textColor = TitleColor
theme.insets = TitleInsets
theme.highlightButtonColor = TabsButtonUX.TitleColor
theme.highlightTextColor = TabsButtonUX.TitleBackgroundColor
theme.highlightBorderColor = TabsButtonUX.TitleBackgroundColor
themes[Theme.NormalMode] = theme
return themes
}()
}
class TabsButton: UIControl {
fileprivate var theme: Theme = TabsButtonUX.Themes[Theme.NormalMode]!
override var isHighlighted: Bool {
didSet {
if isHighlighted {
borderColor = theme.highlightBorderColor!
titleBackgroundColor = theme.highlightButtonColor
textColor = theme.highlightTextColor
} else {
borderColor = theme.borderColor!
titleBackgroundColor = theme.backgroundColor
textColor = theme.textColor
}
}
}
override var transform: CGAffineTransform {
didSet {
clonedTabsButton?.transform = transform
}
}
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = TabsButtonUX.TitleFont
label.layer.cornerRadius = TabsButtonUX.CornerRadius
label.textAlignment = NSTextAlignment.center
label.isUserInteractionEnabled = false
return label
}()
lazy var insideButton: UIView = {
let view = UIView()
view.clipsToBounds = false
view.isUserInteractionEnabled = false
return view
}()
fileprivate lazy var labelBackground: UIView = {
let background = UIView()
background.layer.cornerRadius = TabsButtonUX.CornerRadius
background.isUserInteractionEnabled = false
return background
}()
fileprivate lazy var borderView: InnerStrokedView = {
let border = InnerStrokedView()
border.strokeWidth = TabsButtonUX.BorderStrokeWidth
border.cornerRadius = TabsButtonUX.CornerRadius
border.isUserInteractionEnabled = false
return border
}()
fileprivate var buttonInsets: UIEdgeInsets = TabsButtonUX.TitleInsets
// Used to temporarily store the cloned button so we can respond to layout changes during animation
fileprivate weak var clonedTabsButton: TabsButton?
override init(frame: CGRect) {
super.init(frame: frame)
insideButton.addSubview(labelBackground)
insideButton.addSubview(borderView)
insideButton.addSubview(titleLabel)
addSubview(insideButton)
isAccessibilityElement = true
accessibilityTraits |= UIAccessibilityTraitButton
}
override func updateConstraints() {
super.updateConstraints()
labelBackground.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
borderView.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
titleLabel.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
insideButton.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(self).inset(insets)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func clone() -> UIView {
let button = TabsButton()
button.accessibilityLabel = accessibilityLabel
button.titleLabel.text = titleLabel.text
button.theme = theme
// Copy all of the styable properties over to the new TabsButton
button.titleLabel.font = titleLabel.font
button.titleLabel.textColor = titleLabel.textColor
button.titleLabel.layer.cornerRadius = titleLabel.layer.cornerRadius
button.labelBackground.backgroundColor = labelBackground.backgroundColor
button.labelBackground.layer.cornerRadius = labelBackground.layer.cornerRadius
button.borderView.strokeWidth = borderView.strokeWidth
button.borderView.color = borderView.color
button.borderView.cornerRadius = borderView.cornerRadius
return button
}
func updateTabCount(_ count: Int, animated: Bool = true) {
let currentCount = self.titleLabel.text
let infinity = "\u{221E}"
let countToBe = (count < 100) ? count.description : infinity
// only animate a tab count change if the tab count has actually changed
if currentCount != count.description || (clonedTabsButton?.titleLabel.text ?? count.description) != count.description {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
insideButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = clone() as! TabsButton
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: #selector(TabsButton.cloneDidClickTabs), for: UIControlEvents.touchUpInside)
newTabsButton.titleLabel.text = countToBe
newTabsButton.accessibilityValue = countToBe
superview?.addSubview(newTabsButton)
newTabsButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = self.frame
newTabsButton.insets = insets
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
let frame = self.insideButton.frame
let halfTitleHeight = frame.height / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-(Double.pi / 2)), 1.0, 0.0, 0.0)
newTabsButton.insideButton.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(-(Double.pi / 2)), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.insideButton.layer.transform = CATransform3DIdentity
self.insideButton.layer.transform = oldFlipTransform
self.insideButton.layer.opacity = 0
}
let completion: (Bool) -> Void = { _ in
// Remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.insideButton.layer.opacity = 1
self.insideButton.layer.transform = CATransform3DIdentity
self.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) tab toolbar")
self.titleLabel.text = countToBe
self.accessibilityValue = countToBe
}
if animated {
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions(), animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func cloneDidClickTabs() {
sendActions(for: UIControlEvents.touchUpInside)
}
}
extension TabsButton: Themeable {
func applyTheme(_ themeName: String) {
guard let theme = TabsButtonUX.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
borderColor = theme.borderColor!
borderWidth = theme.borderWidth!
titleFont = theme.font
titleBackgroundColor = theme.backgroundColor
textColor = theme.textColor
insets = theme.insets!
self.theme = theme
}
}
// MARK: UIAppearance
extension TabsButton {
dynamic var borderColor: UIColor {
get { return borderView.color }
set { borderView.color = newValue }
}
dynamic var borderWidth: CGFloat {
get { return borderView.strokeWidth }
set { borderView.strokeWidth = newValue }
}
dynamic var textColor: UIColor? {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
dynamic var titleFont: UIFont? {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
dynamic var titleBackgroundColor: UIColor? {
get { return labelBackground.backgroundColor }
set { labelBackground.backgroundColor = newValue }
}
dynamic var insets: UIEdgeInsets {
get { return buttonInsets }
set {
buttonInsets = newValue
setNeedsUpdateConstraints()
}
}
}
|
mpl-2.0
|
68477d3aa10b0018c6354f81ff23feab
| 37.096886 | 196 | 0.646957 | 5.649051 | false | false | false | false |
crossroadlabs/Swirl
|
Sources/Swirl/TupleRep.swift
|
1
|
11940
|
//===--- TupleRep.swift ------------------------------------------------------===//
//Copyright (c) 2017 Crossroad Labs s.r.o.
//
//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 protocol Boilerplate.TupleProtocol
public protocol ArrayParser {
associatedtype ArrayParseResult
static func parse(array:[Any?]) -> ArrayParseResult
}
public protocol RepRichTuple : TupleProtocol {
associatedtype ColumnsRep : TupleRepProtocol
static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep
}
extension Tuple1 : RepRichTuple {
public typealias ColumnsRep = Tuple1Rep<TypedColumn<A>>
public static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep {
return ColumnsRep(tuple: columns)
}
}
extension Tuple2 : RepRichTuple {
public typealias ColumnsRep = Tuple2Rep<TypedColumn<A>, TypedColumn<B>>
public static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep {
return ColumnsRep(tuple: columns)
}
}
extension Tuple3 : RepRichTuple {
public typealias ColumnsRep = Tuple3Rep<TypedColumn<A>, TypedColumn<B>, TypedColumn<C>>
public static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep {
return ColumnsRep(tuple: columns)
}
}
extension Tuple4 : RepRichTuple {
public typealias ColumnsRep = Tuple4Rep<
TypedColumn<A>,
TypedColumn<B>,
TypedColumn<C>,
TypedColumn<D>>
public static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep {
return ColumnsRep(tuple: columns)
}
}
extension Tuple5 : RepRichTuple {
public typealias ColumnsRep = Tuple5Rep<
TypedColumn<A>,
TypedColumn<B>,
TypedColumn<C>,
TypedColumn<D>,
TypedColumn<E>>
public static func columns(_ columns:ColumnsRep.Tuple.Wrapped) -> ColumnsRep {
return ColumnsRep(tuple: columns)
}
}
public protocol TupleRepProtocol : Rep {
associatedtype Tuple : TupleProtocol
associatedtype Naked
typealias ArrayParseResult = Naked
var tuple:Tuple {get}
var wrapped:Tuple.Wrapped {get}
}
public extension TupleRepProtocol {
public var wrapped: Tuple.Wrapped {
return tuple.tuple
}
public var stripe: [ErasedRep] {
return tuple.stripe.flatMap {$0 as? ErasedRep}.flatMap {$0.stripe}
}
}
//EntityLike
/*public extension TupleRepProtocol {
public typealias Bind = Naked
public func rep() -> [ErasedRep] {
return self.stripe
}
}*/
////////////////////////////////////////////////// ONE //////////////////////////////////////////////////
public protocol Tuple1RepProtocol : TupleRepProtocol {
associatedtype A : Rep
}
public extension Tuple1RepProtocol {
public typealias Tuple = Tuple1<A>
}
public struct Tuple1Rep<AI : Rep> : Tuple1RepProtocol {
public typealias A = AI
public typealias Tuple = Tuple1<A>
public typealias Value = Tuple1<A.Value>
public typealias Naked = Value.Wrapped
public let tuple: Tuple1<A>
public init(tuple: (A)) {
self.tuple = Tuple1<A>(tuple: tuple)
}
public init(_ a:A) {
self.init(tuple: (a))
}
}
////////////////////////////////////////////////// TWO //////////////////////////////////////////////////
public protocol Tuple2RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
}
public extension Tuple2RepProtocol {
public typealias Tuple = Tuple2<A, B>
}
public struct Tuple2Rep<AI : Rep, BI : Rep> : Tuple2RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias Tuple = Tuple2<A, B>
public typealias Value = Tuple2<A.Value, B.Value>
public typealias Naked = Value.Wrapped
public let tuple: Tuple2<A, B>
public init(tuple: (A, B)) {
self.tuple = Tuple2<A, B>(tuple: tuple)
}
public init(_ a:A, _ b:B) {
self.init(tuple: (a, b))
}
}
////////////////////////////////////////////////// THREE //////////////////////////////////////////////////
public protocol Tuple3RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
}
public extension Tuple3RepProtocol {
public typealias Tuple = Tuple3<A, B, C>
}
public struct Tuple3Rep<AI : Rep, BI : Rep, CI : Rep> : Tuple3RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias Tuple = Tuple3<A, B, C>
public typealias Value = Tuple3<A.Value, B.Value, C.Value>
public typealias Naked = Value.Wrapped
public let tuple: Tuple3<A, B, C>
public init(tuple: (A, B, C)) {
self.tuple = Tuple3<A, B, C>(tuple: tuple)
}
public init(_ a:A, _ b:B, _ c:C) {
self.init(tuple: (a, b, c))
}
}
////////////////////////////////////////////////// FOUR //////////////////////////////////////////////////
public protocol Tuple4RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
associatedtype D : Rep
}
public extension Tuple4RepProtocol {
public typealias Tuple = Tuple4<A, B, C, D>
}
public struct Tuple4Rep<AI : Rep, BI : Rep, CI : Rep, DI : Rep> : Tuple4RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias D = DI
public typealias Tuple = Tuple4<A, B, C, D>
public typealias Value = Tuple4<A.Value, B.Value, C.Value, D.Value>
public typealias Naked = Value.Wrapped
public let tuple: Tuple4<A, B, C, D>
public init(tuple: (A, B, C, D)) {
self.tuple = Tuple4<A, B, C, D>(tuple: tuple)
}
public init(_ a:A, _ b:B, _ c:C, _ d:D) {
self.init(tuple: (a, b, c, d))
}
}
////////////////////////////////////////////////// FIVE //////////////////////////////////////////////////
public protocol Tuple5RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
associatedtype D : Rep
associatedtype E : Rep
}
public extension Tuple5RepProtocol {
public typealias Tuple = Tuple5<A, B, C, D, E>
}
public struct Tuple5Rep<AI : Rep, BI : Rep, CI : Rep, DI : Rep, EI : Rep> : Tuple5RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias D = DI
public typealias E = EI
public typealias Tuple = Tuple5<A, B, C, D, E>
public typealias Value = Tuple5<A.Value, B.Value, C.Value, D.Value, E.Value>
public typealias Naked = Value.Wrapped
public let tuple: Tuple5<A, B, C, D, E>
public init(tuple: (A, B, C, D, E)) {
self.tuple = Tuple5<A, B, C, D, E>(tuple: tuple)
}
public init(_ a:A, _ b:B, _ c:C, _ d:D, _ e:E) {
self.init(tuple: (a, b, c, d, e))
}
}
////////////////////////////////////////////////// FOUR //////////////////////////////////////////////////
/*
public protocol Tuple4RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
associatedtype D : Rep
associatedtype Value = (A, B, C, D)
}
public extension Tuple4RepProtocol {
var tuple:(A, B, C, D) {
return value as! (A, B, C, D)
}
}
public extension Tuple4RepProtocol {
public var stripe: [ErasedRep] {
let t = tuple
let s:[ErasedRep] = [t.0, t.1, t.2, t.3]
return s.flatMap {$0.stripe}
}
}
public struct Tuple4Rep<AI : Rep, BI : Rep, CI : Rep, DI : Rep> : Tuple4RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias D = DI
public typealias Tuple = Tuple4<A, B, C, D>
public typealias Value = (A, B, C, D)
public typealias Naked = (A.Value, B.Value, C.Value, D.Value)
public let value:Value
public init(value:Value) {
self.value = value
}
public init(_ a:A, _ b:B, _ c:C, _ d:D) {
self.init(value: (a, b, c, d))
}
}
public extension Tuple4Rep {
static func parse(array:[Any?]) -> Naked {
return (array[0]! as! A.Value, array[1]! as! B.Value, array[2]! as! C.Value, array[3]! as! D.Value)
}
}
////////////////////////////////////////////////// FIVE //////////////////////////////////////////////////
public protocol Tuple5RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
associatedtype D : Rep
associatedtype E : Rep
associatedtype Value = (A, B, C, D, E)
}
public extension Tuple5RepProtocol {
var tuple:(A, B, C, D, E) {
return value as! (A, B, C, D, E)
}
}
public extension Tuple5RepProtocol {
public var stripe: [ErasedRep] {
let t = tuple
let s:[ErasedRep] = [t.0, t.1, t.2, t.3, t.4]
return s.flatMap {$0.stripe}
}
}
public struct Tuple5Rep<AI : Rep, BI : Rep, CI : Rep, DI : Rep, EI : Rep> : Tuple5RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias D = DI
public typealias E = EI
public typealias Value = (A, B, C, D, E)
public typealias Naked = (A.Value, B.Value, C.Value, D.Value, E.Value)
public let value:Value
public init(value:Value) {
self.value = value
}
public init(_ a:A, _ b:B, _ c:C, _ d:D, _ e:E) {
self.init(value: (a, b, c, d, e))
}
}
public extension Tuple5Rep {
static func parse(array:[Any?]) -> Naked {
return (array[0]! as! A.Value, array[1]! as! B.Value, array[2]! as! C.Value, array[3]! as! D.Value, array[4]! as! E.Value)
}
}
////////////////////////////////////////////////// SIX //////////////////////////////////////////////////
public protocol Tuple6RepProtocol : TupleRepProtocol {
associatedtype A : Rep
associatedtype B : Rep
associatedtype C : Rep
associatedtype D : Rep
associatedtype E : Rep
associatedtype F : Rep
associatedtype Value = (A, B, C, D, E, F)
}
public extension Tuple6RepProtocol {
var tuple:(A, B, C, D, E, F) {
return value as! (A, B, C, D, E, F)
}
}
public extension Tuple6RepProtocol {
public var stripe: [ErasedRep] {
let t = tuple
let s:[ErasedRep] = [t.0, t.1, t.2, t.3, t.4, t.5]
return s.flatMap {$0.stripe}
}
}
public struct Tuple6Rep<AI : Rep, BI : Rep, CI : Rep, DI : Rep, EI : Rep, FI : Rep> : Tuple6RepProtocol {
public typealias A = AI
public typealias B = BI
public typealias C = CI
public typealias D = DI
public typealias E = EI
public typealias F = FI
public typealias Value = (A, B, C, D, E, F)
public typealias Naked = (A.Value, B.Value, C.Value, D.Value, E.Value, F.Value)
public let value:Value
public init(value:Value) {
self.value = value
}
public init(_ a:A, _ b:B, _ c:C, _ d:D, _ e:E, _ f:F) {
self.init(value: (a, b, c, d, e, f))
}
}
public extension Tuple6Rep {
static func parse(array:[Any?]) -> Naked {
return (array[0]! as! A.Value,
array[1]! as! B.Value,
array[2]! as! C.Value,
array[3]! as! D.Value,
array[4]! as! E.Value,
array[5]! as! F.Value)
}
}*/
|
apache-2.0
|
b3de16e9196910e3e5fc8fc4534005d7
| 27.361045 | 130 | 0.573116 | 3.708075 | false | false | false | false |
cotkjaer/SilverbackFramework
|
SilverbackFramework/CGPoint.swift
|
1
|
9150
|
//
// CGPoint.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 20/04/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import CoreGraphics
import UIKit
// MARK: - CGPoint
extension CGPoint
{
// public init(_ x: CGFloat, _ y: CGFloat)
// {
// self.x = x
// self.y = y
// }
// MARK: with
public func with(x x: CGFloat) -> CGPoint
{
return CGPoint(x: x, y: y)
}
public func with(y y: CGFloat) -> CGPoint
{
return CGPoint(x: x, y: y)
}
// MARK: distance
public func distanceTo(point: CGPoint) -> CGFloat
{
return sqrt(distanceSquaredTo(point))
}
public func distanceSquaredTo(point: CGPoint) -> CGFloat
{
return pow(x - point.x, 2) + pow(y - point.y, 2)
}
// MARK: mid way
public func midWayTo(p2:CGPoint) -> CGPoint
{
return CGPoint(x: (self.x + p2.x) / 2.0, y: (self.y + p2.y) / 2.0)
}
// MARK: rotation
/// angle is in radians
public mutating func rotate(theta:CGFloat, around center:CGPoint)
{
let sinTheta = sin(theta)
let cosTheta = cos(theta)
let transposedX = x - center.x
let transposedY = y - center.y
x = center.x + (transposedX * cosTheta - transposedY * sinTheta)
y = center.y + (transposedX * sinTheta + transposedY * cosTheta)
}
public func angleToPoint(point: CGPoint) -> CGFloat
{
return atan2(point.y - y, point.x - x)
}
}
public func dot(a: CGPoint, _ b: CGPoint) -> CGFloat
{
return a.x * b.x + a.y * b.y
}
public func distance(a: CGPoint, _ b: CGPoint) -> CGFloat
{
return a.distanceTo(b)
}
public func distanceSquared(a: CGPoint, _ b: CGPoint) -> CGFloat
{
return pow(a.x - b.x, 2) + pow(a.y - b.y, 2)
}
/**
Distance between a line-segment and a point
- parameter lineSegment: line-segment
- parameter point: point
- returns: Minimum distance between a line-segment and a point
*/
public func distance(lineSegment:(CGPoint, CGPoint), _ point: CGPoint) -> CGFloat
{
let v = lineSegment.0
let w = lineSegment.1
let p = point
if v == w { return distance(v, p) }
// Return minimum distance between line segment vw and point p
let l = distanceSquared(v, w)
// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2
let t = dot(p - v, w - v) / l
if t < 0 // Beyond the 'v' end of the segment
{
return distance(p, v)
}
else if t > 1 // Beyond the 'w' end of the segment
{
return distance(p, w)
}
else // Projection falls on the segment
{
let projection = (1-t) * v + t * w// v + t * (w - v)
return distance(p, projection)
}
}
/**
Precise linear interpolation function which guarantees *lerp(a,b,0) == a && lerp(a,b,1) == b*
- parameter a: begin point
- parameter b: end point
- parameter t: 'time' traveled from *a* to *b*, **must** be in the closed unit interval [0,1], defaults to 0.5
- returns: An interpolation between points *a* and *b* for the 'time' parameter *t*
*/
public func lerp(a: CGPoint, _ b: CGPoint, _ t: CGFloat = 0.5) -> CGPoint
{
// Should be return (1-t) * a + t * b
// but this is more effective as it creates only one new CGPoint and performs minimum number of arithmetic operations
return CGPoint(x: (1-t) * a.x + t * b.x, y: (1-t) * a.y + t * b.y)
}
/**
Linear interpolation for array of points, usefull for calculating Bézier curve points using DeCasteljau subdivision algorithm
- parameter ps: the points
- parameter t: 'time' traveled from *ps[i]* to *ps[i+1]*, **must** be in the closed unit interval [0,1], defaults to 0.5
- returns: If *ps.count < 2 ps* itself will be returned. Else an interpolation between all neighbouring points in *ps* for the 'time' parameter *t* (the resulting Array will be one shorter than *ps*)
*/
public func lerp(ps: [CGPoint], t: CGFloat) -> [CGPoint]
{
let count = ps.count
if count < 2
{
return ps
}
return Array(1..<count).map( { lerp(ps[$0-1], ps[$0], t) } )
}
public func rotate(point p1:CGPoint, radians: CGFloat, around p2:CGPoint) -> CGPoint
{
let sinTheta = sin(radians)
let cosTheta = cos(radians)
let transposedX = p1.x - p2.x
let transposedY = p1.y - p2.y
return CGPoint(x: p2.x + (transposedX * cosTheta - transposedY * sinTheta),
y: p2.y + (transposedX * sinTheta + transposedY * cosTheta))
}
public func distanceFrom(p1:CGPoint, to p2:CGPoint) -> CGFloat
{
return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2))
}
public func midPoint(between p1:CGPoint, and p2:CGPoint) -> CGPoint
{
return CGPoint(x: (p1.x + p2.x) / 2.0, y: (p1.y + p2.y) / 2.0)
}
// MARK: - Equatable
extension CGPoint//: Equatable
{
public func isEqualTo(point: CGPoint, withPrecision precision:CGFloat) -> Bool
{
return distanceTo(point) < abs(precision)
}
public func isEqualTo(point:CGPoint) -> Bool
{
return self == point
}
}
//public func ==(lhs: CGPoint, rhs: CGPoint) -> Bool
//{
// return lhs.x == rhs.x && lhs.y == rhs.y
//}
public func isEqual(p1: CGPoint, p2: CGPoint, withPrecision precision:CGFloat) -> Bool
{
return distanceFrom(p1, to:p2) < abs(precision)
}
// MARK: - Comparable
extension CGPoint: Comparable
{
}
/// CAVEAT: first y then x comparison
public func > (p1: CGPoint, p2: CGPoint) -> Bool
{
return (p1.y < p2.y) || ((p1.y == p2.y) && (p1.x < p2.x))
}
public func < (p1: CGPoint, p2: CGPoint) -> Bool
{
return (p1.y > p2.y) || ((p1.y == p2.y) && (p1.x > p2.x))
}
// MARK: - Operators
public func + (p1: CGPoint, p2: CGPoint) -> CGPoint
{
return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y)
}
public func += (inout p1: CGPoint, p2: CGPoint)
{
p1.x += p2.x
p1.y += p2.y
}
public prefix func - (p: CGPoint) -> CGPoint
{
return CGPoint(x: -p.x, y: -p.y)
}
public func - (p1: CGPoint, p2: CGPoint) -> CGPoint
{
return CGPoint(x: p1.x - p2.x, y: p1.y - p2.y)
}
public func -= (inout p1: CGPoint, p2: CGPoint)
{
p1.x -= p2.x
p1.y -= p2.y
}
public func + (point: CGPoint, size: CGSize) -> CGPoint
{
return CGPoint(x: point.x + size.width, y: point.y + size.height)
}
public func += (inout point: CGPoint, size: CGSize)
{
point.x += size.width
point.y += size.height
}
public func - (point: CGPoint, size: CGSize) -> CGPoint
{
return CGPoint(x: point.x - size.width, y: point.y - size.height)
}
public func -= (inout point: CGPoint, size: CGSize)
{
point.x -= size.width
point.y -= size.height
}
public func * (factor: CGFloat, point: CGPoint) -> CGPoint
{
return CGPoint(x: point.x * factor, y: point.y * factor)
}
public func * (point: CGPoint, factor: CGFloat) -> CGPoint
{
return CGPoint(x: point.x * factor, y: point.y * factor)
}
public func *= (inout point: CGPoint, factor: CGFloat)
{
point.x *= factor
point.y *= factor
}
public func / (point: CGPoint, factor: CGFloat) -> CGPoint
{
return CGPoint(x: point.x / factor, y: point.y / factor)
}
public func /= (inout point: CGPoint, factor: CGFloat)
{
point.x /= factor
point.y /= factor
}
public func * (point: CGPoint, transform: CGAffineTransform) -> CGPoint
{
return CGPointApplyAffineTransform(point, transform)
}
public func *= (inout point: CGPoint, transform: CGAffineTransform)
{
point = point * transform//CGPointApplyAffineTransform(point, transform)
}
//MARK: - Random
public extension CGPoint
{
/**
Create a random CGFloat
- parameter center: center, defaults to (0, 0)
- parameter lowerRadius: bounds, defaults to 0
- parameter upperRadius: bounds
:return: random number CGFloat
*/
static func random(center: CGPoint = CGPointZero, lowerRadius: CGFloat = 0, upperRadius: CGFloat) -> CGPoint
{
let upper = max(abs(upperRadius), abs(lowerRadius))
let lower = min(abs(upperRadius), abs(lowerRadius))
let radius = CGFloat.random(lower: lower, upper: upper)
let alpha = CGFloat.random(lower: 0, upper: 2 * π)
return CGPoint(x: center.x + cos(alpha) * radius, y: center.y + sin(alpha) * radius)
}
/**
Create a random CGFloat
- parameter path,: bounding path for random point
- parameter lowerRadius: bounds, defaults to 0
- parameter upperRadius: bounds
:return: random number CGFloat
*/
static func random(insidePath: UIBezierPath) -> CGPoint?
{
let bounds = insidePath.bounds
for _ in 0...100
{
let point =
CGPoint(x: CGFloat.random(lower: bounds.minX, upper: bounds.maxX),
y: CGFloat.random(lower: bounds.minY, upper: bounds.maxY))
if insidePath.containsPoint(point)
{
return point
}
}
return nil
}
}
|
mit
|
01e48e13865191f62afc2e59240d094a
| 23.853261 | 200 | 0.601028 | 3.305385 | false | false | false | false |
jyxia/PennApps-Scouter-iOS
|
FilmScouter/FilterTableViewController.swift
|
1
|
6522
|
//
// FilterTableViewController.swift
// FilmScouter
//
// Created by Jinyue Xia on 9/5/15.
// Copyright (c) 2015 Jinyue Xia. All rights reserved.
//
import UIKit
class FilterTableViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var searchTextView: UITextField!
@IBOutlet weak var startDatePicker: UIDatePicker!
@IBOutlet weak var endDatePicker: UIDatePicker!
var startDatePickerIsShowing = false
var endDatePickerIsShowing = false
override func viewDidLoad() {
super.viewDidLoad()
startDatePicker.addTarget(self, action: Selector("startDataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
endDatePicker.addTarget(self, action: Selector("endDataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
self.hideStartPickerCell()
self.hideEndPickerCell()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = true
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func textFieldDidEndEditing(textField: UITextField) {
self.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 1 || section == 2) {
return 2
}
return 1
}
override func tableView(tableview: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height = super.tableView(tableview, heightForRowAtIndexPath: indexPath)
if indexPath.section == 1 {
if indexPath.row == 1 {
if !self.startDatePickerIsShowing {
height = 0
}
}
}
if indexPath.section == 2 {
if indexPath.row == 1 {
if !self.endDatePickerIsShowing {
height = 0
}
}
}
return height
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.searchTextView.resignFirstResponder()
if indexPath.section == 1 {
if indexPath.row == 0 {
if self.startDatePickerIsShowing {
self.hideStartPickerCell()
} else {
self.showStartDatePickerCell()
}
}
}
if indexPath.section == 2 {
if indexPath.row == 0 {
if self.endDatePickerIsShowing {
self.hideEndPickerCell()
} else {
self.showEndDatePickerCell()
}
}
}
if indexPath.section == 0 || indexPath.section == 3 {
if self.startDatePickerIsShowing {
self.hideStartPickerCell()
}
if self.endDatePickerIsShowing {
self.hideEndPickerCell()
}
}
if indexPath.section == 3 {
self.performSegueWithIdentifier("priceSeg", sender: self)
}
}
func startDataPickerChanged(datePicker:UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
var strDate = dateFormatter.stringFromDate(startDatePicker.date)
var indexPath = NSIndexPath(forRow: 0, inSection: 1)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
cell.detailTextLabel!.text = strDate
}
}
func endDataPickerChanged(datePicker:UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
var endDate = dateFormatter.stringFromDate(endDatePicker.date)
var indexPath = NSIndexPath(forRow: 0, inSection: 2)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
cell.detailTextLabel!.text = endDate
}
}
private func showStartDatePickerCell() {
self.startDatePickerIsShowing = true
self.tableView.beginUpdates()
self.tableView.endUpdates()
self.startDatePicker.hidden = false
}
private func hideStartPickerCell() {
self.startDatePickerIsShowing = false
self.tableView.beginUpdates()
self.tableView.endUpdates()
self.startDatePicker.hidden = true
}
private func showEndDatePickerCell() {
self.endDatePickerIsShowing = true
self.tableView.beginUpdates()
self.tableView.endUpdates()
self.endDatePicker.hidden = false
}
private func hideEndPickerCell() {
self.endDatePickerIsShowing = false
self.tableView.beginUpdates()
self.tableView.endUpdates()
self.endDatePicker.hidden = true
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "unwindToHomeSeg" {
}
if segue.identifier == "priceSeg" {
var indexPath = NSIndexPath(forRow: 0, inSection: 3)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
let destController = segue.destinationViewController as! PriceListingTableViewController
destController.selectedPrice = cell.detailTextLabel!.text
}
}
}
@IBAction func passedPriceSelection (segue: UIStoryboardSegue) {
if let priceViewController = segue.sourceViewController as? PriceListingTableViewController {
var selectedPrice = priceViewController.selectedPrice
var indexPath = NSIndexPath(forRow: 0, inSection: 3)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
cell.detailTextLabel!.text = selectedPrice
}
self.navigationController?.popViewControllerAnimated(true) }
}
}
|
mit
|
52c01d5c8ebed37db00f4a64a9a04ec0
| 34.835165 | 132 | 0.629408 | 5.593482 | false | false | false | false |
xiongxiong/TagList
|
Framework/SwiftTagList/SeparatorWrapper.swift
|
1
|
2835
|
//
// info.swift
// TagList
//
// Created by 王继荣 on 15/12/2016.
// Copyright © 2016 wonderbear. All rights reserved.
//
import UIKit
public class SeparatorWrapper: UIView {
var info: SeparatorInfo
var target: UIView?
public init(info: SeparatorInfo) {
self.info = info
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override var intrinsicContentSize: CGSize {
let targetSize = target?.intrinsicContentSize ?? CGSize.zero
return CGSize(width: targetSize.width + info.size.width + info.margin.left + info.margin.right, height: targetSize.height)
}
public func wrap(_ target: UIView) -> UIView {
self.target = target
subviews.forEach { (view) in
view.removeFromSuperview()
}
arrangeViews(target: target)
return self
}
func arrangeViews(target: UIView) {
addSubview(target)
let icon = UIImageView(image: info.image)
icon.contentMode = .scaleAspectFit
addSubview(icon)
target.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: target, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: target, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: target, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
icon.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: icon, attribute: .leading, relatedBy: .equal, toItem: target, attribute: .trailing, multiplier: 1, constant: info.margin.left))
addConstraint(NSLayoutConstraint(item: icon, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: info.size.width))
addConstraint(NSLayoutConstraint(item: icon, attribute: .centerY, relatedBy: .equal, toItem: target, attribute: .centerY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: icon, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: info.size.height))
addConstraint(NSLayoutConstraint(item: icon, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: info.margin.right * -1))
}
}
public struct SeparatorInfo {
public var image: UIImage = UIImage()
public var size: CGSize = CGSize.zero
public var margin: UIEdgeInsets = UIEdgeInsets.zero
}
|
mit
|
51d2a80291c28512a92fbfccb62d3b52
| 41.848485 | 179 | 0.680339 | 4.517572 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKitUI/view model/TKUIAutocompletionViewModel.swift
|
1
|
7411
|
//
// TKUIAutocompletionViewModel.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 05.07.18.
// Copyright © 2018 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import RxCocoa
import RxSwift
import TripKit
class TKUIAutocompletionViewModel {
struct Section {
let identifier: String
var items: [Item]
var title: String? = nil
}
enum Item: Equatable {
case currentLocation
case autocompletion(AutocompletionItem)
case action(ActionItem)
fileprivate var result: TKAutocompletionResult? {
switch self {
case .autocompletion(let item): return item.completion
case .action, .currentLocation: return nil
}
}
fileprivate var selection: Single<TKAutocompletionSelection>? {
switch self {
case .currentLocation: return .just(.annotation(TKLocationManager.shared.currentLocation))
case .autocompletion(let item): return item.completion.annotation
case .action: return nil
}
}
var provider: TKAutocompleting? {
switch self {
case .currentLocation: return nil
case .autocompletion(let item): return item.provider
case .action(let item): return item.provider
}
}
var isAction: Bool {
switch self {
case .action: return true
case .autocompletion, .currentLocation: return false
}
}
}
struct AutocompletionItem: Equatable {
let index: Int
let completion: TKAutocompletionResult
let includeAccessory: Bool
var image: UIImage { completion.image }
var title: String { completion.title }
var subtitle: String? { completion.subtitle }
var accessoryAccessibilityLabel: String? { includeAccessory ? completion.accessoryAccessibilityLabel : nil }
var accessoryImage: UIImage? { includeAccessory ? completion.accessoryButtonImage : nil }
var showFaded: Bool { !completion.isInSupportedRegion }
var provider: TKAutocompleting? { completion.provider as? TKAutocompleting }
}
struct ActionItem: Equatable {
static func == (lhs: TKUIAutocompletionViewModel.ActionItem, rhs: TKUIAutocompletionViewModel.ActionItem) -> Bool {
lhs.title == rhs.title
}
fileprivate let provider: TKAutocompleting
let title: String
fileprivate init?(provider: TKAutocompleting) {
guard let title = provider.additionalActionTitle() else { return nil }
self.provider = provider
self.title = title
}
}
required init(
providers: [TKAutocompleting],
includeCurrentLocation: Bool = false,
searchText: Observable<(String, forced: Bool)>,
selected: Signal<Item>,
accessorySelected: Signal<Item>? = nil,
refresh: Signal<Void> = .never(),
biasMapRect: Driver<MKMapRect> = .just(.null)
) {
let errorPublisher = PublishSubject<Error>()
sections = Self.buildSections(providers, searchText: searchText, refresh: refresh, biasMapRect: biasMapRect, includeCurrentLocation: includeCurrentLocation, includeAccessory: accessorySelected != nil)
.asDriver(onErrorDriveWith: Driver.empty())
selection = selected
.compactMap(\.selection)
.asObservable()
.flatMapLatest { fetched -> Observable<TKAutocompletionSelection> in
return fetched
.asObservable()
.catch { error in
errorPublisher.onNext(error)
return Observable.empty()
}
}
.asSignal(onErrorSignalWith: .empty())
accessorySelection = (accessorySelected ?? .empty())
.compactMap(\.result)
.asObservable()
.flatMapLatest { result -> Observable<TKAutocompletionSelection> in
return result.annotation
.asObservable()
.catch { error in
errorPublisher.onNext(error)
return Observable.empty()
}
}
.asSignal(onErrorSignalWith: .empty())
triggerAction = selected
.filter(\.isAction)
.compactMap(\.provider)
error = errorPublisher.asSignal(onErrorSignalWith: .never())
}
let sections: Driver<[Section]>
let selection: Signal<TKAutocompletionSelection>
let accessorySelection: Signal<TKAutocompletionSelection>
/// Fires when user taps on the "additional action" element of a `TKAutocompleting`
/// provider. If that's the case, you should call `triggerAdditional` on it.
let triggerAction: Signal<TKAutocompleting>
let error: Signal<Error>
}
// MARK: - Helpers
extension TKUIAutocompletionViewModel {
private static func buildSections(_ providers: [TKAutocompleting], searchText: Observable<(String, forced: Bool)>, refresh: Signal<Void>, biasMapRect: Driver<MKMapRect>, includeCurrentLocation: Bool, includeAccessory: Bool) -> Observable<[Section]> {
let additionalItems = providers
.compactMap(ActionItem.init)
.map { Item.action($0) }
let additionalSection = additionalItems.isEmpty ? [] : [Section(identifier: "actions", items: additionalItems, title: Loc.MoreResults)]
let searchTrigger = refresh.asObservable().startWith(())
return searchTrigger
.flatMapLatest { providers.autocomplete(searchText, mapRect: biasMapRect.asObservable()) }
.map { $0.buildSections(includeCurrentLocation: includeCurrentLocation, includeAccessory: includeAccessory) + additionalSection }
}
}
extension Array where Element == TKAutocompletionResult {
fileprivate func buildSections(includeCurrentLocation: Bool, includeAccessory: Bool) -> [TKUIAutocompletionViewModel.Section] {
var sections: [TKUIAutocompletionViewModel.Section] = []
if includeCurrentLocation {
sections.append(TKUIAutocompletionViewModel.Section(identifier: "current-location", items: [.currentLocation]))
}
let items = enumerated().map { tuple -> TKUIAutocompletionViewModel.Item in
let autocompletion = TKUIAutocompletionViewModel.AutocompletionItem(index: tuple.offset, completion: tuple.element, includeAccessory: includeAccessory)
return .autocompletion(autocompletion)
}
if !items.isEmpty {
sections.append(TKUIAutocompletionViewModel.Section(identifier: "results", items: items))
}
return sections
}
}
extension TKAutocompletionResult {
fileprivate var annotation: Single<TKAutocompletionSelection> {
guard let provider = provider as? TKAutocompleting else {
assertionFailure()
return Single.error(NSError(code: 18376, message: "Bad provider!"))
}
return provider.annotation(for: self)
.map {
if let annotation = $0 {
return .annotation(annotation)
} else {
return .result(self)
}
}
}
}
// MARK: - RxDataSource protocol conformance
extension TKUIAutocompletionViewModel.Item: IdentifiableType {
typealias Identity = String
var identity: Identity {
switch self {
case .currentLocation: return Loc.CurrentLocation
case .action(let action): return action.title
case .autocompletion(let autocompletion): return "\(autocompletion.index)-\(autocompletion.title)"
}
}
}
extension TKUIAutocompletionViewModel.Section: AnimatableSectionModelType {
typealias Item = TKUIAutocompletionViewModel.Item
init(original: TKUIAutocompletionViewModel.Section, items: [Item]) {
self = original
self.items = items
}
var identity: String { identifier }
}
|
apache-2.0
|
c17a789af1823b52930e93ef08bd9246
| 30.662393 | 252 | 0.697125 | 4.851997 | false | false | false | false |
naoyashiga/AkutagawaPrize
|
AkutagawaPrize/CarouselCollectionViewCell.swift
|
1
|
2799
|
//
// CarouselCollectionViewCell.swift
// AkutagawaPrize
//
// Created by naoyashiga on 2015/10/15.
// Copyright © 2015年 naoyashiga. All rights reserved.
//
import UIKit
import WebImage
protocol BrowserOpenerDelegate {
func openBrowser(url: NSURL)
}
struct ContentCollectionReuseId {
static let cell = "ContentCollectionViewCell"
}
@available(iOS 9.0, *)
class CarouselCollectionViewCell: BaseCarouselCollectionViewCell, UICollectionViewDataSource {
@IBOutlet var collectionView: UICollectionView!
var books = [Book]()
var browserOpenerDelegate: BrowserOpenerDelegate?
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.applyCellNib(cellNibName: ContentCollectionReuseId.cell)
baseCollectionView = collectionView
setCollectionView()
}
func setCollectionView() {
carouselCellSize.width = collectionView.bounds.width
carouselCellSize.height = collectionView.bounds.height
collectionView.backgroundColor = UIColor.viewBackgroundColor()
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return BookManager.sharedInstance.books.count
return books.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ContentCollectionReuseId.cell, forIndexPath: indexPath) as! ContentCollectionViewCell
let book = books[indexPath.row]
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.hexStr("#aaaaaa", alpha: 1.0)
} else {
cell.backgroundColor = UIColor.grayColor()
}
cell.titleLabel.text = book.title
cell.authorLabel.text = book.author
cell.yearLabel.text = String(book.year)
cell.numberLabel.text = String(book.number)
cell.imageView.sd_setImageWithURL(
book.imageURL,
completed: { image, error, type, URL in
})
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let book = books[indexPath.row]
guard let linkURL = book.linkURL else {
return
}
browserOpenerDelegate?.openBrowser(linkURL)
}
}
|
mit
|
545ff2c6b9ec7d6f2b479172a9b08ec7
| 28.431579 | 158 | 0.660229 | 5.536634 | false | false | false | false |
naoyashiga/LegendTV
|
LegendTV/HomeCollectionViewController.swift
|
1
|
9553
|
//
// HomeCollectionViewController.swift
// housoushitsu
//
// Created by naoyashiga on 2015/07/04.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
struct homeReuseId {
static let cell = "VideoListCollectionViewCell"
static let headerView = "HomeHeaderView"
}
class HomeCollectionViewController: BaseCollectionViewController {
private var sections = [[Story]]()
private var queries = [String]()
private var seriesNames = [String]()
private var kikakuNames = [String]()
private var searchText = ""
private var sectionIndex = 0
private let sectionStoriesCount = 3
private let sectionCount = 3
private var headerIndex = 0
var kikakuData: NSDictionary = NSDictionary()
var kikakuJSON: JSON = ""
override func viewDidLoad() {
super.viewDidLoad()
setKikakuJSON()
setStories()
collectionView?.applyHeaderNib(headerNibName: homeReuseId.headerView)
collectionView?.applyCellNib(cellNibName: homeReuseId.cell)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: private method
override func refresh() {
finishReloadData() {
self.refreshControl.endRefreshing()
}
}
private func finishReloadData(callback:() -> ()) {
sections = [[Story]]()
queries = [String]()
seriesNames = [String]()
kikakuNames = [String]()
sectionIndex = 0
print(sections.count)
setKikakuJSON()
setStories()
callback()
}
func setKikakuJSON() {
if let path = NSBundle.mainBundle().pathForResource("Kikaku", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
kikakuJSON = json
}
}
}
func setSearchText() -> String {
let itemCount = kikakuJSON["items"].count
let item = kikakuJSON["items"][Int.random(0...(itemCount - 1))]
let kikakuList = item["kikakuList"]
var randomKikaku = kikakuList[Int.random(0...(kikakuList.count - 1))]
if let randomKikakuNotOptional = randomKikaku["query"].string {
if randomKikakuNotOptional.isEmpty {
randomKikaku = kikakuList[Int.random(0...kikakuList.count)]
print("empty")
if let second = randomKikaku["query"].string {
if second.isEmpty {
//2回目も空
randomKikaku["query"] = randomKikaku["name"]
// println("queryをnameと同じにする")
}
}
}
} else {
// println("query optional")
// println("queryをnameと同じにする")
randomKikaku["query"] = randomKikaku["name"]
}
if let query = randomKikaku["query"].string {
let encodingRandomQuery = query.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
queries.append(encodingRandomQuery)
if let seriesName = item["seriesName"].string {
seriesNames.append(seriesName)
}
if let kikakuName = randomKikaku["name"].string {
kikakuNames.append(kikakuName)
}
return encodingRandomQuery
} else {
print("query error")
return "ガキの使い".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
}
func setStories() {
let searchWord = setSearchText()
let requestURL = Config.REQUEST_SEARCH_URL + "q=\(searchWord)&part=snippet&maxResults=\(sectionStoriesCount)"
Alamofire.request(.GET, requestURL).responseJSON { reponse in
var responseJSON: JSON
if reponse.result.isFailure {
responseJSON = JSON.null
} else {
responseJSON = SwiftyJSON.JSON(reponse.result.value!)
}
var stories = [Story]()
if let items = responseJSON["items"].array {
for item in items {
let duration = Story(json: item)
stories.append(duration)
}
self.sectionIndex++
self.sections.append(stories)
if self.sectionIndex < self.sectionCount {
self.setStories()
} else {
self.collectionView?.reloadData()
self.activityIndicator.stopAnimating()
}
}
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sectionCount
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionStoriesCount
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: homeReuseId.headerView, forIndexPath: indexPath) as! HomeHeaderView
if queries.count == sectionCount {
headerView.headerTitleLabel.text = kikakuNames[indexPath.section]
}
return setCornerRadius(headerView: headerView)
default:
assert(false, "error")
return UICollectionReusableView()
}
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(homeReuseId.cell, forIndexPath: indexPath) as! VideoListCollectionViewCell
if sections.count != sectionCount {
// println("not fill sectionCount")
return cell
}
let sectionStories = sections[indexPath.section]
let story = sectionStories[indexPath.row]
//通常の背景
let backgroundView = UIView()
backgroundView.bounds = cell.bounds
backgroundView.backgroundColor = UIColor.cellLightBackgroundColor()
cell.backgroundView = backgroundView
//選択時の背景
let selectedBackgroundView = UIView()
selectedBackgroundView.bounds = cell.bounds
selectedBackgroundView.backgroundColor = UIColor.cellSelectedBackgroundColor()
cell.selectedBackgroundView = selectedBackgroundView
cell.titleLabel.text = story.title
cell.thumbNailImageView.loadingStoryImageBySDWebImage(story)
VideoInfo.getDurationTimes(story.videoID){ contentDetails in
if contentDetails.isEmpty {
cell.durationLabel.text = "??:??"
} else {
let duration = contentDetails[0].duration
cell.durationLabel.text = VideoInfo.getDurationStr(duration)
}
}
VideoInfo.getStatistics(story.videoID){ statistics in
if statistics.isEmpty {
cell.viewCountLabel.text = "?"
cell.likeCountLabel.text = "?"
} else {
cell.viewCountLabel.text = statistics[0].viewCount
cell.likeCountLabel.text = statistics[0].likeCount
}
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(homeReuseId.cell, forIndexPath: indexPath) as! VideoListCollectionViewCell
let sectionStories = sections[indexPath.section]
let story = sectionStories[indexPath.row]
story.seriesName = seriesNames[indexPath.section]
// let vc = TransitionManager.sharedManager.getDetailViewController(story: story)
// navigationController?.pushViewController(vc, animated: true)
//get Data for History
var callBackCount = 0
getDurationTimeAndStatistics(story: story, cell: cell) { cellHavingData in
callBackCount++
if callBackCount == 2 {
self.delegate?.saveHistory(story: story, cell: cellHavingData)
self.delegate?.sendVideoData(story: story)
self.delegate?.applyForControlBarData(story: story)
}
}
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: cellSize.width, height: 45)
}
}
|
mit
|
95df9b910d3fc1efad09a4963f355ea4
| 33.863971 | 180 | 0.593799 | 5.614565 | false | false | false | false |
manhpro/website
|
iOSQuiz-master/iOSQuiz-master/LeoiOSQuiz/Classes/AppDefines/Strings.swift
|
1
|
607
|
//
// Strings.swift
// LeoiOSQuiz
//
// Created by NeoLap on 4/15/17.
// Copyright © 2017 Leo LE. All rights reserved.
//
import UIKit
let kStringUserLocationTitle = "My Location"
//reviews
let kStringNumberReviews = "%d Reviews"
let kStringRestaurant = "Restaurant"
let kStringDismiss = "Dismiss"
let kStringSpace = " "
struct AlertVC {
enum AlertButtonTitle: String {
case ok = "OK"
case cancel = "Cancel"
}
enum AlertTitle: String {
case error = "Error"
}
enum AlertMessage: String {
case authenFail = "Authenticate failed"
}
}
|
cc0-1.0
|
bab1fc1f6ab5dcdd43599fd26619b81b
| 17.363636 | 49 | 0.635314 | 3.607143 | false | false | false | false |
at-internet/atinternet-ios-swift-sdk
|
Tracker/Tracker/NuggAd.swift
|
1
|
2627
|
/*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// NuggAd.swift
// Tracker
//
import UIKit
public class NuggAd: BusinessObject {
let key = "nuggad"
lazy public var data: [String: Any] = [String: Any]()
/// Set parameters in buffer
override func setEvent() {
if let optPlugin = self.tracker.configuration.parameters["plugins"] {
if (optPlugin.range(of: "nuggad") != nil) {
let option = ParamOption()
option.append = true
option.encode = true
_ = self.tracker.setParam("stc", value: [self.key: self.data], options:option)
}
else {
self.tracker.delegate?.warningDidOccur("NuggAd not enabled")
}
} else {
self.tracker.delegate?.warningDidOccur("NuggAd not enabled")
}
}
}
public class NuggAds {
/// Tracker instance
var tracker: Tracker
/**
NuggAds initializer
- parameter tracker: the tracker instance
- returns: NuggAds instance
*/
init(tracker: Tracker) {
self.tracker = tracker
}
/**
Set NuggAd data
- parameter data: NuggAd response data
- returns: NuggAd instance
*/
public func add(_ data: [String: Any]) -> NuggAd {
let ad = NuggAd(tracker: tracker)
ad.data = data
tracker.businessObjects[ad.id] = ad
return ad
}
}
|
mit
|
4c7764c9d65978e4301b72475d817fd7
| 31.012195 | 141 | 0.666667 | 4.389632 | false | false | false | false |
zivboy/jetstream-ios
|
JetstreamDemos/JetstreamDemos/ShapesDemoViewController.swift
|
4
|
3353
|
//
// ShapesDemoViewController.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import Jetstream
class ShapesDemoViewController: UIViewController, NSURLConnectionDataDelegate {
var scope = Scope(name: "Canvas")
var canvas = Canvas()
var client: Client?
var session: Session?
override func viewDidLoad() {
super.viewDidLoad()
title = "Shapes Demo"
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
self.view.addGestureRecognizer(tapRecognizer)
scope.root = canvas
canvas.observeCollectionAdd(self, key: "shapes") { (element: Shape) in
let shapeView = ShapeView(shape: element)
self.view.addSubview(shapeView)
}
}
func handleTap(recognizer: UITapGestureRecognizer) {
let shape = Shape()
shape.color = shapeColors[Int(arc4random_uniform(UInt32(shapeColors.count)))]
var point = recognizer.locationInView(self.view)
shape.x = point.x - shape.width / 2
shape.y = point.y - shape.height / 2
canvas.shapes.append(shape)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
showLoader()
let options = WebSocketConnectionOptions(url: NSURL(string: "ws://" + host + ":3000")!)
client = Client(transportAdapterFactory: { WebSocketTransportAdapter(options: options) })
client?.connect()
client?.onSession.listenOnce(self) { [unowned self] in self.sessionDidStart($0) }
}
func sessionDidStart(session: Session) {
self.session = session
session.fetch(scope) { error in
if error != nil {
self.alertError("Error fetching scope", message: "\(error)")
} else {
self.hideLoader()
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
hideLoader()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
client?.onSession.removeListener(self)
client?.close()
client = nil
}
}
|
mit
|
17c4a154e839e6542ae277e8ebedc261
| 35.846154 | 97 | 0.668058 | 4.644044 | false | false | false | false |
practicalswift/swift
|
validation-test/compiler_crashers_fixed/01536-getselftypeforcontainer.swift
|
65
|
517
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A {
typealias f = a
func a: b.e = [Byte]]
self[Int) {
return g<T -> T.E == "[T : C {
typealias f : A.f = B<T>
|
apache-2.0
|
16a682d506276290cc66a948923a5892
| 35.928571 | 79 | 0.705996 | 3.423841 | false | false | false | false |
trashkalmar/omim
|
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewTaxiCell.swift
|
3
|
1963
|
@objc(MWMRoutePreviewTaxiCell)
final class RoutePreviewTaxiCell: UICollectionViewCell {
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var title: UILabel! {
didSet {
title.font = UIFont.bold14()
title.textColor = UIColor.blackPrimaryText()
}
}
@IBOutlet private weak var info: UILabel! {
didSet {
info.font = UIFont.regular14()
info.textColor = UIColor.blackSecondaryText()
}
}
@objc func config(type: MWMRoutePreviewTaxiCellType, title: String, eta: String, price: String, currency: String) {
let iconImage = { () -> UIImage in
switch type {
case .taxi: return #imageLiteral(resourceName: "icTaxiTaxi")
case .uber: return #imageLiteral(resourceName: "icTaxiUber")
case .yandex: return #imageLiteral(resourceName: "icTaxiYandex")
}
}
let titleString = { () -> String in
switch type {
case .taxi: fallthrough
case .uber: return title
case .yandex: return L("yandex_taxi_title")
}
}
let priceString = { () -> String in
switch type {
case .taxi: fallthrough
case .uber: return price
case .yandex:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currency
formatter.maximumFractionDigits = 0
if let number = UInt(price), let formattedPrice = formatter.string(from: NSNumber(value: number)) {
return formattedPrice
} else {
return "\(currency) \(price)"
}
}
}
let timeString = { () -> String in
let timeValue = DateComponentsFormatter.etaString(from: TimeInterval(eta)!)!
let format = L("taxi_wait").replacingOccurrences(of: "%s", with: "%@")
return String(format: format, arguments: [timeValue])
}
icon.image = iconImage()
self.title.text = titleString()
info.text = "~ \(priceString()) • \(timeString())"
}
}
|
apache-2.0
|
7e6c09a858421439da2bf0e823df3b77
| 30.126984 | 117 | 0.631311 | 4.387025 | false | false | false | false |
SeriousChoice/SCSwift
|
SCSwift/Form/SCSwitchTableCell.swift
|
1
|
2946
|
//
// SCSwitchTableCell.swift
// SCSwiftExample
//
// Created by Nicola Innocenti on 08/01/2022.
// Copyright © 2022 Nicola Innocenti. All rights reserved.
//
import UIKit
public protocol SCSwitchTableCellDelegate : AnyObject {
func scSwitchTableCellDidChangeSelection(cell: SCSwitchTableCell)
}
public class SCSwitchTableCell: UITableViewCell {
public var lblTitle: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
public var swSwitch: UISwitch = {
let uiswitch = UISwitch()
return uiswitch
}()
public weak var delegate: SCSwitchTableCellDelegate?
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
clipsToBounds = true
setupLayout()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupLayout() {
let margin = SCFormViewController.cellsMargin
contentView.addSubview(lblTitle)
lblTitle.sc_pinEdge(toSuperViewEdge: .top, withOffset: margin)
lblTitle.sc_pinEdge(toSuperViewEdge: .leading, withOffset: 20)
lblTitle.sc_pinEdge(toSuperViewEdge: .bottom, withOffset: -margin)
swSwitch.setOn(false, animated: false)
swSwitch.addTarget(self, action: #selector(switchDidChangeValue(sender:)), for: .valueChanged)
contentView.addSubview(swSwitch)
swSwitch.sc_pinEdge(toSuperViewEdge: .trailing, withOffset: -20)
swSwitch.sc_pinEdge(.leading, toEdge: .trailing, ofView: lblTitle, withOffset: 20, withRelation: .greaterOrEqual)
swSwitch.sc_alignAxis(axis: .vertical, toView: lblTitle)
}
override public func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public override func configure(with row: SCFormRow) {
if let title = row.title {
let text = row.mandatory ? "\(title) *" : title
if let attributed = NSMutableAttributedString(html: text) {
attributed.addAttributes([
.font: lblTitle.font ?? UIFont.systemFont(ofSize: 17),
.foregroundColor: lblTitle.textColor ?? UIColor.black
], range: NSRange(location: 0, length: attributed.length))
lblTitle.attributedText = attributed
} else {
lblTitle.text = ""
}
} else {
lblTitle.text = ""
}
swSwitch.isOn = (row.value as? Bool) ?? false
}
@objc func switchDidChangeValue(sender: UISwitch) {
delegate?.scSwitchTableCellDidChangeSelection(cell: self)
}
}
|
mit
|
6d849c90d5bdf25f58d5c8116ba5ada4
| 33.647059 | 121 | 0.633277 | 4.835796 | false | false | false | false |
ripventura/VCHTTPConnect
|
Example/Pods/EFQRCode/Source/QRPolynomial.swift
|
2
|
3404
|
//
// QRRSBlock.swift
// EFQRCode
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS) || os(macOS)
#else
struct QRPolynomial {
private var numbers: [Int]
init!(_ nums: Int..., shift: Int = 0) {
self.init(nums, shift: shift)
}
init?(_ nums: [Int], shift: Int = 0) {
guard nums.count != 0 else { return nil }
var offset = 0
while offset < nums.count && nums[offset] == 0 {
offset += 1
}
self.numbers = [Int](repeating: 0, count: nums.count - offset + shift)
for i in 0..<nums.count - offset {
self.numbers[i] = nums[i + offset]
}
}
func get(index: Int) -> Int {
return numbers[index]
}
subscript(index: Int) -> Int {
return get(index: index)
}
var count: Int {
return numbers.count
}
func multiplying(_ e: QRPolynomial) -> QRPolynomial {
var nums = [Int](repeating: 0, count: count + e.count - 1)
for i in 0..<count {
for j in 0..<e.count {
nums[i + j] ^= QRMath.gexp(QRMath.glog(self[i]) + QRMath.glog(e[j]))
}
}
return QRPolynomial(nums)!
}
func moded(by e: QRPolynomial) -> QRPolynomial {
if (count - e.count < 0) {
return self
}
let ratio = QRMath.glog(self[0]) - QRMath.glog(e[0])
var num = [Int](repeating: 0, count: count)
for i in 0..<count {
num[i] = self[i]
}
for i in 0..<e.count {
num[i] ^= QRMath.gexp(QRMath.glog(e[i]) + ratio)
}
return QRPolynomial(num)!.moded(by: e)
}
static func errorCorrectPolynomial(ofLength errorCorrectLength: Int) -> QRPolynomial? {
guard var a = QRPolynomial(1) else { return nil }
for i in 0..<errorCorrectLength {
a = a.multiplying(QRPolynomial(1, QRMath.gexp(i))!)
}
return a
}
}
#endif
|
mit
|
56f9e0ed35775bdcfebb668386f913bc
| 35.212766 | 95 | 0.552291 | 4.081535 | false | false | false | false |
designatednerd/GoCubs
|
GoCubs/DataSources/CubsGameDataSource.swift
|
1
|
2372
|
//
// CubsGameDataSource.swift
// GoCubs
//
// Created by Ellen Shapiro on 10/11/15.
// Copyright © 2015 Designated Nerd Software. All rights reserved.
//
import Foundation
import UIKit
class CubsGameDataSource: NSObject {
let games: [CubsGame]
init(tableView: UITableView) {
//Load in the string
guard let path = Bundle.main.path(forResource: "cubs2016", ofType: "csv") else {
fatalError("Could not create path for CSV!")
}
var csvString: String
do {
csvString = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
} catch {
csvString = ""
}
let lines = csvString.components(separatedBy: .newlines)
var gameBuilder = [CubsGame]()
for line in lines {
if line.endIndex != line.startIndex {
let game = CubsGame(gameString: line)
gameBuilder.append(game)
}
}
//Sort in reverse date order
gameBuilder.sort {
$0.date.compare($1.date as Date) == ComparisonResult.orderedDescending
}
self.games = gameBuilder
super.init()
tableView.dataSource = self
tableView.reloadData()
}
//MARK: Confgiuration Helper
func game(forCell cell: CubsGameCell, in tableView: UITableView) -> CubsGame {
guard let indexPath = tableView.indexPath(for: cell) else {
fatalError("There is no index path for this cell!")
}
return self.games[indexPath.row]
}
}
//MARK: - UITableViewDataSource
extension CubsGameDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.games.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CubsGameCell.identifier) as? CubsGameCell else {
fatalError("Wrong cell type!")
}
let game = self.games[indexPath.row]
cell.configure(forGame: game)
return cell
}
}
|
mit
|
9b7cae38000e711b54efbbf7eab588b9
| 26.894118 | 119 | 0.59806 | 4.751503 | false | false | false | false |
MTTHWBSH/Gaggle
|
Gaggle/Views/IntroView.swift
|
1
|
1618
|
//
// IntroView.swift
// Gaggle
//
// Created by Matthew Bush on 6/11/15.
// Copyright (c) 2015 Matthew Bush. All rights reserved.
//
import UIKit
class IntroView: UIView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
var title: String? {
didSet {
titleLabel.text = ""
setup()
}
}
var subtitle: String? {
didSet {
subtitleLabel.text = ""
setup()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
class func initWith(_ title: String, subtitle: String, image: UIImage) -> IntroView {
guard let introView: IntroView = Bundle.main.loadNibNamed("IntroView", owner: self, options: nil)?.first as? IntroView else { return IntroView() }
introView.title = title.capitalized
introView.subtitle = subtitle.capitalized
introView.imageView.image = image
return introView
}
func setup() {
self.backgroundColor = UIColor.white
titleLabel.textColor = Style.grayColor
subtitleLabel.textColor = Style.grayColor
}
func animateText() {
titleLabel.text = ""
subtitleLabel.text = ""
titleLabel.layer.removeAllAnimations()
subtitleLabel.layer.removeAllAnimations()
Animation.punchText(title!, label: titleLabel) {
Animation.punchText(self.subtitle!, label: self.subtitleLabel, completion: nil)
}
}
}
|
gpl-2.0
|
f41514eccb9e475b38fdbf4b9f71696f
| 25.096774 | 154 | 0.595797 | 4.772861 | false | false | false | false |
dalbin/Eureka
|
Example/Example/ViewController.swift
|
1
|
38802
|
// ViewController.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.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 Eureka
import CoreLocation
//MARK: HomeViewController
class HomeViewController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
ImageRow.defaultCellUpdate = { cell, row in
cell.accessoryView?.layer.cornerRadius = 17
cell.accessoryView?.frame = CGRectMake(0, 0, 34, 34)
}
form +++=
Section(footer: "These are 9 ButtonRow rows") {
$0.header = HeaderFooterView<EurekaLogoView>(HeaderFooterProvider.Class)
}
<<< ButtonRow("Rows") {
$0.title = $0.tag
$0.presentationMode = .SegueName(segueName: "RowsExampleViewControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Native iOS Event Form") { row in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "NativeEventsFormNavigationControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) })
}
<<< ButtonRow("Accesory View Navigation") { (row: ButtonRow) in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "AccesoryViewControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Custom Cells") { (row: ButtonRow) -> () in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "CustomCellsControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Customization of rows with text input") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "FieldCustomizationControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Hidden rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "HiddenRowsControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Disabled rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "DisabledRowsControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Formatters") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "FormattersControllerSegue", completionCallback: nil)
}
<<< ButtonRow("Inline rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .SegueName(segueName: "InlineRowsControllerSegue", completionCallback: nil)
}
}
}
//MARK: Emoji
typealias Emoji = String
let 👦🏼 = "👦🏼", 🍐 = "🍐", 💁🏻 = "💁🏻", 🐗 = "🐗", 🐼 = "🐼", 🐻 = "🐻", 🐖 = "🐖", 🐡 = "🐡"
//Mark: RowsExampleViewController
class RowsExampleViewController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
URLRow.defaultCellUpdate = { cell, row in cell.textField.textColor = .blueColor() }
LabelRow.defaultCellUpdate = { cell, row in cell.detailTextLabel?.textColor = .orangeColor() }
CheckRow.defaultCellSetup = { cell, row in cell.tintColor = .orangeColor() }
DateRow.defaultRowInitializer = { row in row.minimumDate = NSDate() }
form =
Section()
<<< LabelRow () {
$0.title = "LabelRow"
$0.value = "tap the row"
}
.onCellSelection { $0.cell.detailTextLabel?.text? += " 🇺🇾 " }
<<< DateRow() { $0.value = NSDate(); $0.title = "DateRow" }
<<< CheckRow() {
$0.title = "CheckRow"
$0.value = true
}
<<< SwitchRow() {
$0.title = "SwitchRow"
$0.value = true
}
+++ Section("SegmentedRow examples")
<<< SegmentedRow<String>() { $0.options = ["One", "Two", "Three"] }
<<< SegmentedRow<Emoji>(){
$0.title = "Who are you?"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻 ]
$0.value = 🍐
}
+++ Section("Selectors Rows Examples")
<<< ActionSheetRow<String>() {
$0.title = "ActionSheetRow"
$0.selectorTitle = "Your favourite player?"
$0.options = ["Diego Forlán", "Edinson Cavani", "Diego Lugano", "Luis Suarez"]
$0.value = "Luis Suarez"
}
<<< AlertRow<Emoji>() {
$0.title = "AlertRow"
$0.selectorTitle = "Who is there?"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 👦🏼
}.onChange { row in
print(row.value)
}
.onPresent{ _, to in
to.view.tintColor = .purpleColor()
}
<<< PushRow<Emoji>() {
$0.title = "PushRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 👦🏼
$0.selectorTitle = "Choose an Emoji!"
}
<<< LocationRow(){
$0.title = "LocationRow"
$0.value = CLLocation(latitude: -34.91, longitude: -56.1646)
}
<<< ImageRow(){
$0.title = "ImageRow"
}
<<< MultipleSelectorRow<Emoji>() {
$0.title = "MultipleSelectorRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = [👦🏼, 🍐, 🐗]
}
.onPresent { from, to in
to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: from, action: "multipleSelectorDone:")
}
+++ Section("Generic picker")
<<< PickerRow<String>("Picker Row") { (row : PickerRow<String>) -> Void in
row.options = []
for i in 1...10{
row.options.append("option \(i)")
}
}
+++ Section("FieldRow examples")
<<< TextRow() {
$0.title = "TextRow"
$0.placeholder = "Placeholder"
}
<<< DecimalRow() {
$0.title = "DecimalRow"
$0.value = 5
}
<<< URLRow() {
$0.title = "URLRow"
$0.value = NSURL(string: "http://xmartlabs.com")
}
<<< PhoneRow() {
$0.title = "PhoneRow (disabled)"
$0.value = "+598 9898983510"
$0.disabled = true
}
<<< NameRow() {
$0.title = "NameRow"
}
<<< PasswordRow() {
$0.title = "PasswordRow"
$0.value = "password"
}
<<< IntRow() {
$0.title = "IntRow"
$0.value = 2015
}
<<< EmailRow() {
$0.title = "EmailRow"
$0.value = "[email protected]"
}
<<< TwitterRow() {
$0.title = "TwitterRow"
$0.value = "@xmartlabs"
}
<<< AccountRow() {
$0.title = "AccountRow"
$0.placeholder = "Placeholder"
}
<<< ZipCodeRow() {
$0.title = "ZipCodeRow"
$0.placeholder = "90210"
}
}
func multipleSelectorDone(item:UIBarButtonItem) {
navigationController?.popViewControllerAnimated(true)
}
}
//MARK: Custom Cells Example
class CustomCellsController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section() {
var header = HeaderFooterView<EurekaLogoViewNib>(HeaderFooterProvider.NibFile(name: "EurekaSectionHeader", bundle: nil))
header.onSetupView = { (view, section, form) -> () in
view.imageView.alpha = 0;
UIView.animateWithDuration(2.0, animations: { [weak view] in
view?.imageView.alpha = 1
})
view.layer.transform = CATransform3DMakeScale(0.9, 0.9, 1)
UIView.animateWithDuration(1.0, animations: { [weak view] in
view?.layer.transform = CATransform3DIdentity
})
}
$0.header = header
}
+++ Section("WeekDay cell")
<<< WeekDayRow(){
$0.value = [.Monday, .Wednesday, .Friday]
}
<<< TextFloatLabelRow() {
$0.title = "Float Label Row, type something to see.."
}
<<< IntFloatLabelRow() {
$0.title = "Float Label Row, type something to see.."
}
}
}
//MARK: Field row customization Example
class FieldRowCustomizationController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section(header: "Default field rows", footer: "Rows with title have a right-aligned text field.\nRows without title have a left-aligned text field.\nBut this can be changed...")
<<< NameRow() {
$0.title = "Your name:"
$0.placeholder = "(right alignment)"
}
.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
<<< NameRow() {
$0.placeholder = "Name (left alignment)"
}
.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
+++ Section("Customized Alignment")
<<< NameRow() {
$0.title = "Your name:"
}.cellUpdate { cell, row in
cell.textField.textAlignment = .Left
cell.textField.placeholder = "(left alignment)"
}
<<< NameRow().cellUpdate { cell, row in
cell.textField.textAlignment = .Right
cell.textField.placeholder = "Name (right alignment)"
}
+++ Section(header: "Customized Text field width", footer: "Eureka allows us to set up a specific UITextField width using textFieldPercentage property. In the section above we have also right aligned the textLabels.")
<<< NameRow() {
$0.title = "Title"
$0.textFieldPercentage = 0.6
$0.placeholder = "textFieldPercentage = 0.6"
}
.cellUpdate {
$0.cell.textField.textAlignment = .Left
$0.cell.textLabel?.textAlignment = .Right
}
<<< NameRow() {
$0.title = "Another Title"
$0.textFieldPercentage = 0.6
$0.placeholder = "textFieldPercentage = 0.6"
}
.cellUpdate {
$0.cell.textField.textAlignment = .Left
$0.cell.textLabel?.textAlignment = .Right
}
<<< NameRow() {
$0.title = "One more"
$0.textFieldPercentage = 0.7
$0.placeholder = "textFieldPercentage = 0.7"
}
.cellUpdate {
$0.cell.textField.textAlignment = .Left
$0.cell.textLabel?.textAlignment = .Right
}
+++ Section("TextAreaRow")
<<< TextAreaRow() { $0.placeholder = "TextAreaRow" }
}
}
//MARK: Navigation Accessory View Example
class NavigationAccessoryController : FormViewController {
var navigationOptionsBackup : RowNavigationOptions?
override func viewDidLoad() {
super.viewDidLoad()
navigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow)
navigationOptionsBackup = navigationOptions
form = Section(header: "Settings", footer: "These settings change how the navigation accessory view behaves")
<<< SwitchRow("set_none") {
$0.title = "Navigation accessory view"
$0.value = self.navigationOptions != .Disabled
}.onChange { [weak self] in
if $0.value == true {
self?.navigationOptions = self?.navigationOptionsBackup
self?.form.rowByTag("set_disabled")?.baseValue = self?.navigationOptions?.contains(.StopDisabledRow)
self?.form.rowByTag("set_skip")?.baseValue = self?.navigationOptions?.contains(.SkipCanNotBecomeFirstResponderRow)
self?.form.rowByTag("set_disabled")?.updateCell()
self?.form.rowByTag("set_skip")?.updateCell()
}
else {
self?.navigationOptionsBackup = self?.navigationOptions
self?.navigationOptions = .Disabled
}
}
<<< CheckRow("set_disabled") {
$0.title = "Stop at disabled row"
$0.value = self.navigationOptions?.contains(.StopDisabledRow)
$0.hidden = "$set_none == false" // .Predicate(NSPredicate(format: "$set_none == false"))
}.onChange { [weak self] row in
if row.value ?? false {
self?.navigationOptions = self?.navigationOptions?.union(.StopDisabledRow)
}
else{
self?.navigationOptions = self?.navigationOptions?.subtract(.StopDisabledRow)
}
}
<<< CheckRow("set_skip") {
$0.title = "Skip non first responder view"
$0.value = self.navigationOptions?.contains(.SkipCanNotBecomeFirstResponderRow)
$0.hidden = "$set_none == false"
}.onChange { [weak self] row in
if row.value ?? false {
self?.navigationOptions = self?.navigationOptions?.union(.SkipCanNotBecomeFirstResponderRow)
}
else{
self?.navigationOptions = self?.navigationOptions?.subtract(.SkipCanNotBecomeFirstResponderRow)
}
}
+++
NameRow() { $0.title = "Your name:" }
<<< PasswordRow() { $0.title = "Your password:" }
+++
Section()
<<< SegmentedRow<Emoji>() {
$0.title = "Favourite food:"
$0.options = [🐗, 🐖, 🐡, 🍐]
}
<<< PhoneRow() { $0.title = "Your phone number" }
<<< URLRow() {
$0.title = "Disabled"
$0.disabled = true
}
<<< TextRow() { $0.title = "Your father's name"}
<<< TextRow(){ $0.title = "Your mother's name"}
}
}
//MARK: Native Event Example
class NativeEventNavigationController: UINavigationController, RowControllerType {
var completionCallback : ((UIViewController) -> ())?
}
class NativeEventFormViewController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
initializeForm()
self.navigationItem.leftBarButtonItem?.target = self
self.navigationItem.leftBarButtonItem?.action = "cancelTapped:"
}
private func initializeForm() {
form =
TextRow("Title").cellSetup { cell, row in
cell.textField.placeholder = row.tag
}
<<< TextRow("Location").cellSetup {
$0.cell.textField.placeholder = $0.row.tag
}
+++
SwitchRow("All-day") {
$0.title = $0.tag
}.onChange { [weak self] row in
let startDate: DateTimeInlineRow! = self?.form.rowByTag("Starts")
let endDate: DateTimeInlineRow! = self?.form.rowByTag("Ends")
if row.value ?? false {
startDate.dateFormatter?.dateStyle = .MediumStyle
startDate.dateFormatter?.timeStyle = .NoStyle
endDate.dateFormatter?.dateStyle = .MediumStyle
endDate.dateFormatter?.timeStyle = .NoStyle
}
else {
startDate.dateFormatter?.dateStyle = .ShortStyle
startDate.dateFormatter?.timeStyle = .ShortStyle
endDate.dateFormatter?.dateStyle = .ShortStyle
endDate.dateFormatter?.timeStyle = .ShortStyle
}
startDate.updateCell()
endDate.updateCell()
startDate.inlineRow?.updateCell()
endDate.inlineRow?.updateCell()
}
<<< DateTimeInlineRow("Starts") {
$0.title = $0.tag
$0.value = NSDate().dateByAddingTimeInterval(60*60*24)
}
.onChange { [weak self] row in
let endRow: DateTimeInlineRow! = self?.form.rowByTag("Ends")
if row.value?.compare(endRow.value!) == .OrderedDescending {
endRow.value = NSDate(timeInterval: 60*60*24, sinceDate: row.value!)
endRow.cell!.backgroundColor = .whiteColor()
endRow.updateCell()
}
}
.onExpandInlineRow { cell, row, inlineRow in
inlineRow.cellUpdate { [weak self] cell, dateRow in
let allRow: SwitchRow! = self?.form.rowByTag("All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .Date
}
else {
cell.datePicker.datePickerMode = .DateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
<<< DateTimeInlineRow("Ends"){
$0.title = $0.tag
$0.value = NSDate().dateByAddingTimeInterval(60*60*25)
}
.onChange { [weak self] row in
let startRow: DateTimeInlineRow! = self?.form.rowByTag("Starts")
if row.value?.compare(startRow.value!) == .OrderedAscending {
row.cell!.backgroundColor = .redColor()
}
else{
row.cell!.backgroundColor = .whiteColor()
}
row.updateCell()
}
.onExpandInlineRow { cell, row, inlineRow in
inlineRow.cellUpdate { [weak self] cell, dateRow in
let allRow: SwitchRow! = self?.form.rowByTag("All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .Date
}
else {
cell.datePicker.datePickerMode = .DateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
form +++=
PushRow<RepeatInterval>("Repeat") {
$0.title = $0.tag
$0.options = RepeatInterval.allValues
$0.value = .Never
}
form +++=
PushRow<EventAlert>() {
$0.title = "Alert"
$0.options = EventAlert.allValues
$0.value = .Never
}
.onChange { [weak self] row in
if row.value == .Never {
if let second : PushRow<EventAlert> = self?.form.rowByTag("Another Alert"), let secondIndexPath = second.indexPath() {
row.section?.removeAtIndex(secondIndexPath.row)
}
}
else{
guard let _ : PushRow<EventAlert> = self?.form.rowByTag("Another Alert") else {
let second = PushRow<EventAlert>("Another Alert") {
$0.title = $0.tag
$0.value = .Never
$0.options = EventAlert.allValues
}
row.section?.insert(second, atIndex: row.indexPath()!.row + 1)
return
}
}
}
form +++=
PushRow<EventState>("Show As") {
$0.title = "Show As"
$0.options = EventState.allValues
}
form +++=
URLRow("URL") {
$0.placeholder = "URL"
}
<<< TextAreaRow("notes") {
$0.placeholder = "Notes"
}
}
func cancelTapped(barButtonItem: UIBarButtonItem) {
(navigationController as? NativeEventNavigationController)?.completionCallback?(self)
}
enum RepeatInterval : String, CustomStringConvertible {
case Never = "Never"
case Every_Day = "Every Day"
case Every_Week = "Every Week"
case Every_2_Weeks = "Every 2 Weeks"
case Every_Month = "Every Month"
case Every_Year = "Every Year"
var description : String { return rawValue }
static let allValues = [Never, Every_Day, Every_Week, Every_2_Weeks, Every_Month, Every_Year]
}
enum EventAlert : String, CustomStringConvertible {
case Never = "None"
case At_time_of_event = "At time of event"
case Five_Minutes = "5 minutes before"
case FifTeen_Minutes = "15 minutes before"
case Half_Hour = "30 minutes before"
case One_Hour = "1 hour before"
case Two_Hour = "2 hours before"
case One_Day = "1 day before"
case Two_Days = "2 days before"
var description : String { return rawValue }
static let allValues = [Never, At_time_of_event, Five_Minutes, FifTeen_Minutes, Half_Hour, One_Hour, Two_Hour, One_Day, Two_Days]
}
enum EventState {
case Busy
case Free
static let allValues = [Busy, Free]
}
}
//MARK: HiddenRowsExample
class HiddenRowsExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
TextRow.defaultCellUpdate = { cell, row in
cell.textLabel?.font = UIFont.italicSystemFontOfSize(12)
}
form = Section("What do you want to talk about:")
<<< SegmentedRow<String>("segments"){
$0.options = ["Sport", "Music", "Films"]
$0.value = "Films"
}
+++ Section(){
$0.tag = "sport_s"
$0.hidden = "$segments != 'Sport'" // .Predicate(NSPredicate(format: "$segments != 'Sport'"))
}
<<< TextRow(){
$0.title = "Which is your favourite soccer player?"
}
<<< TextRow(){
$0.title = "Which is your favourite coach?"
}
<<< TextRow(){
$0.title = "Which is your favourite team?"
}
+++ Section(){
$0.tag = "music_s"
$0.hidden = "$segments != 'Music'"
}
<<< TextRow(){
$0.title = "Which music style do you like most?"
}
<<< TextRow(){
$0.title = "Which is your favourite singer?"
}
<<< TextRow(){
$0.title = "How many CDs have you got?"
}
+++ Section(){
$0.tag = "films_s"
$0.hidden = "$segments != 'Films'"
}
<<< TextRow(){
$0.title = "Which is your favourite actor?"
}
<<< TextRow(){
$0.title = "Which is your favourite film?"
}
+++ Section()
<<< SwitchRow("Show Next Row"){
$0.title = $0.tag
}
<<< SwitchRow("Show Next Section"){
$0.title = $0.tag
$0.hidden = .Function(["Show Next Row"], { form -> Bool in
let row: RowOf<Bool>! = form.rowByTag("Show Next Row")
return row.value ?? false == false
})
}
+++ Section(footer: "This section is shown only when 'Show Next Row' switch is enabled"){
$0.hidden = .Function(["Show Next Section"], { form -> Bool in
let row: RowOf<Bool>! = form.rowByTag("Show Next Section")
return row.value ?? false == false
})
}
<<< TextRow() {
$0.placeholder = "Gonna dissapear soon!!"
}
}
}
//MARK: DisabledRowsExample
class DisabledRowsExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form = Section()
<<< SegmentedRow<String>("segments"){
$0.options = ["Enabled", "Disabled"]
$0.value = "Disabled"
}
<<< TextRow(){
$0.title = "choose enabled, disable above..."
$0.disabled = "$segments = 'Disabled'"
}
<<< SwitchRow("Disable Next Section?"){
$0.title = $0.tag
$0.disabled = "$segments = 'Disabled'"
}
+++ Section()
<<< TextRow() {
$0.title = "Gonna be disabled soon.."
$0.disabled = Condition.Function(["Disable Next Section?"], { (form) -> Bool in
let row: SwitchRow! = form.rowByTag("Disable Next Section?")
return row.value ?? false
})
}
+++ Section()
<<< SegmentedRow<String>(){
$0.options = ["Always Disabled"]
$0.disabled = true
}
}
}
//MARK: FormatterExample
class FormatterExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++ Section("Number formatters")
<<< DecimalRow(){
$0.useFormatterDuringInput = true
$0.title = "Currency style"
$0.value = 2015
let formatter = CurrencyFormatter()
formatter.locale = .currentLocale()
formatter.numberStyle = .CurrencyStyle
$0.formatter = formatter
}
<<< DecimalRow(){
$0.title = "Scientific style"
$0.value = 2015
let formatter = NSNumberFormatter()
formatter.locale = .currentLocale()
formatter.numberStyle = .ScientificStyle
$0.formatter = formatter
}
<<< IntRow(){
$0.title = "Spell out style"
$0.value = 2015
let formatter = NSNumberFormatter()
formatter.locale = .currentLocale()
formatter.numberStyle = .SpellOutStyle
$0.formatter = formatter
}
+++ Section("Date formatters")
<<< DateRow(){
$0.title = "Short style"
$0.value = NSDate()
let formatter = NSDateFormatter()
formatter.locale = .currentLocale()
formatter.dateStyle = .ShortStyle
$0.dateFormatter = formatter
}
<<< DateRow(){
$0.title = "Long style"
$0.value = NSDate()
let formatter = NSDateFormatter()
formatter.locale = .currentLocale()
formatter.dateStyle = .LongStyle
$0.dateFormatter = formatter
}
+++ Section("Other formatters")
<<< DecimalRow(){
$0.title = "Energy: Jules to calories"
$0.value = 100.0
let formatter = NSEnergyFormatter()
$0.formatter = formatter
}
<<< IntRow(){
$0.title = "Weight: Kg to lb"
$0.value = 1000
$0.formatter = NSMassFormatter()
}
}
class CurrencyFormatter : NSNumberFormatter, FormatterProtocol {
override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
guard obj != nil else { return false }
var str : String
str = string.stringByReplacingOccurrencesOfString(currencySymbol, withString: "")
str = str.stringByReplacingOccurrencesOfString(currencyGroupingSeparator, withString: "")
guard let i = Float(str) else { return false }
obj.memory = NSNumber(float: i)
return true
}
func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.positionFromPosition(position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position
}
}
}
class InlineRowsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form.inlineRowHideOptions = InlineRowHideOptions.AnotherInlineRowIsShown.union(.FirstResponderChanges)
form
+++ Section("Automatically Hide Inline Rows?")
<<< SwitchRow() {
$0.title = "Hides when another inline row is shown"
$0.value = true
}
.onChange { [weak form] in
if $0.value == true {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.union(.AnotherInlineRowIsShown)
}
else {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.subtract(.AnotherInlineRowIsShown)
}
}
<<< SwitchRow() {
$0.title = "Hides when the First Responder changes"
$0.value = true
}
.onChange { [weak form] in
if $0.value == true {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.union(.FirstResponderChanges)
}
else {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.subtract(.FirstResponderChanges)
}
}
+++ Section()
<<< DateInlineRow() {
$0.title = "DateInlineRow"
$0.value = NSDate()
}
<<< TimeInlineRow(){
$0.title = "TimeInlineRow"
$0.value = NSDate()
}
<<< DateTimeInlineRow(){
$0.title = "DateTimeInlineRow"
$0.value = NSDate()
}
<<< CountDownInlineRow(){
$0.title = "CountDownInlineRow"
let dateComp = NSDateComponents()
dateComp.hour = 18
dateComp.minute = 33
dateComp.timeZone = NSTimeZone.systemTimeZone()
$0.value = NSCalendar.currentCalendar().dateFromComponents(dateComp)
}
+++ Section("Generic inline picker")
<<< PickerInlineRow<NSDate>("PickerInlineRow") { (row : PickerInlineRow<NSDate>) -> Void in
row.title = row.tag
row.displayValueFor = {
guard let date = $0 else{
return nil
}
let year = NSCalendar.currentCalendar().component(.Year, fromDate: date)
return "Year \(year)"
}
row.options = []
var date = NSDate()
for _ in 1...10{
row.options.append(date)
date = date.dateByAddingTimeInterval(60*60*24*365)
}
row.value = row.options[0]
}
}
}
class EurekaLogoViewNib: UIView {
@IBOutlet weak var imageView: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class EurekaLogoView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let imageView = UIImageView(image: UIImage(named: "Eureka"))
imageView.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
imageView.autoresizingMask = .FlexibleWidth
self.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
imageView.contentMode = .ScaleAspectFit
self.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
eefaebe23527b7291873141c57550e9a
| 37.989899 | 229 | 0.449223 | 5.587724 | false | false | false | false |
yisimeng/YSMFactory-swift
|
YSMFactory-swift/Vendor/YSMPageView/YSMPageView.swift
|
1
|
2678
|
//
// YSMPageView.swift
// YSMFactory-swift
//
// Created by 忆思梦 on 2016/12/5.
// Copyright © 2016年 忆思梦. All rights reserved.
//
import UIKit
class YSMPageView: UIView {
fileprivate var titles:[String]
fileprivate var childVCs:[UIViewController]
fileprivate var parentVC:UIViewController
fileprivate var style:YSMPageViewStye
fileprivate lazy var titleView :YSMPageTitleView = {
let titleViewFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.style.titleViewHeight)
let titleView = YSMPageTitleView(frame: titleViewFrame, titles: self.titles, style:self.style)
titleView.backgroundColor = UIColor.randomColor()
titleView.delegate = self
return titleView
}()
fileprivate lazy var contentView :YSMPageContentView = {
let contentViewFrame = CGRect(x: 0, y: self.style.titleViewHeight, width: self.bounds.width, height: self.bounds.height - self.style.titleViewHeight)
let contentView = YSMPageContentView(frame: contentViewFrame, childVCs: self.childVCs, parentVC: self.parentVC, style:self.style)
contentView.delegate = self
return contentView
}()
init(frame: CGRect ,titles : [String] , viewControllers:[UIViewController] ,parentController:UIViewController, style:YSMPageViewStye) {
assert(titles.count == viewControllers.count, "title与控制器的数目不符")
assert(viewControllers.count > 0, "至少要有一个控制器")
self.titles = titles;
self.childVCs = viewControllers;
self.parentVC = parentController;
self.style = style;
super.init(frame: frame)
prepareUI();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - prepareUI
extension YSMPageView{
fileprivate func prepareUI() {
addSubview(titleView)
addSubview(contentView)
}
}
extension YSMPageView:YSMPageTitleViewDelegate,YSMPageContentViewDelegate{
//YSMPageTitleViewDelegate
func titleView(_ titleView: YSMPageTitleView, didSelectIndex targetIndex: Int) {
contentView.set(currentIndex: targetIndex)
}
//YSMPageContentViewDelegate
func contentViewDidEndScroll(_ contentView: YSMPageContentView, _ targetIndex: Int) {
titleView.adjustCurrentLabelCentered(targetIndex)
}
func contentView(_ contentView:YSMPageContentView, from currentIndex:Int,scrollingTo targetIndex:Int, _ progress:CGFloat){
titleView.scrollingTitle(from: currentIndex, to: targetIndex, with: progress)
}
}
|
mit
|
50c7045d8d31680013134888943d82b2
| 34.026667 | 157 | 0.69547 | 4.584642 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/BaseTest/BaseTest/Class_Struct_Enum/keywordSummary.swift
|
1
|
1508
|
//
// keywordSummary.swift
// BaseTest
//
// Created by wuyp on 2016/12/26.
// Copyright © 2016年 raymond. All rights reserved.
//
import Foundation
protocol Container {
/// associatedtype:主要用于确定类型,子类自行去确定
associatedtype ItemType
mutating func append(_ item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct StringStack: Container {
typealias ItemType = String
var items = [String]()
mutating func push(_ item: ItemType) {
items.append(item)
}
mutating func pop() -> ItemType {
return items.removeLast()
}
mutating func append(_ item: String) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> ItemType {
return items[i]
}
mutating func changeSelf() {
self = StringStack()
}
}
class SomeBaseClass {
class func printClassName() {
print("Some base class")
}
}
class SomeSubClass: SomeBaseClass {
let string: String
required init(string: String) {
self.string = string
}
override class func printClassName() {
print("Some Sub class")
}
}
class TestKeywordSummary: NSObject {
class func test() {
let sub: SomeBaseClass = SomeBaseClass()
if type(of: sub) === sub.self {
print("------0")
} else {
print("------1")
}
}
}
|
apache-2.0
|
488ae76854489aad7b506ac158e43cb8
| 17.884615 | 51 | 0.562797 | 4.149296 | false | false | false | false |
qds-hoi/suracare
|
suracare/suracare/Core/Library/SwiftValidator/Rules/ExactLengthRule.swift
|
1
|
1642
|
//
// ExactLengthRule.swift
// Validator
//
// Created by Jeff Potter on 2/3/16.
// Copyright © 2016 jpotts18. All rights reserved.
//
import Foundation
/**
`ExactLengthRule` is a subclass of Rule that is used to make sure a the text of a field is an exact length.
*/
public class ExactLengthRule : Rule {
/// parameter message: String of error message.
private var message : String = "Must be at most 16 characters long"
/// parameter length: Integer value string length
private var length : Int
/**
Initializes an `ExactLengthRule` object to validate the text of a field against an exact length.
- parameter length: Integer value of exact string length being specified.
- parameter message: String of error message.
- returns: An initialized `ExactLengthRule` object, or nil if an object could not be created for some reason. that would not result in an exception.
*/
public init(length: Int, message : String = "Must be exactly %ld characters long"){
self.length = length
self.message = NSString(format: message, self.length) as String
}
/**
Used to validate a field.
- parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
return value.characters.count == length
}
/**
Displays error message if a field fails validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
}
|
mit
|
5713f865304fae5c489832b7a13b81de
| 31.84 | 153 | 0.666057 | 4.558333 | false | false | false | false |
schrockblock/eson
|
Example/Tests/SerializationTest.swift
|
1
|
2382
|
//
// SerializationTest.swift
// Eson
//
// Created by Elliot Schrock on 1/25/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import Eson
import Eson_Example
class SerializationTest: QuickSpec {
override func spec() {
describe("Eson") {
it("can serialize a class to JSON") {
let neo = Human.generateNeo()
let eson = Eson()
let optionalJson = eson.toJsonDictionary(neo)
expect(optionalJson).toNot(beNil())
if let json = optionalJson {
print(json)
expect(json["name"]).notTo(beNil())
expect(json["name"] as? String).to(equal(neo.name))
expect(json["title"]).notTo(beNil())
expect(json["title"] as? String).to(equal(neo.title))
expect(json["age"]).notTo(beNil())
expect(json["age"] as? Int).to(equal(neo.age))
expect(json["has_taken_red_pill"]).notTo(beNil())
if let hasTakenRedPill = json["has_taken_red_pill"] as? NSNumber {
expect(hasTakenRedPill.boolValue).to(equal(neo.hasTakenRedPill?.boolValue))
}
expect(json["id"]).notTo(beNil())
expect(json["id"] as? Int).to(equal(neo.objectId))
let ship: [String : AnyObject]? = json["ship"] as? [String : AnyObject]
expect(ship?["id"] as? Int).to(equal(neo.ship!.objectId))
expect(ship?["name"] as? String).to(equal(neo.ship!.name))
}
}
it("can serialize generic class") {
let neo = Human.generateNeo()
let jsonApiObject = JsonApiDataObject<Human>.generateDataObject(neo)
let optionalJson = Eson().toJsonDictionary(jsonApiObject)
expect(optionalJson).toNot(beNil())
if let json = optionalJson {
expect(json["attributes"]).notTo(beNil())
expect(json["attributes"]?["name"]).notTo(beNil())
expect(String(describing: (json["attributes"]?["name"])!)).to(equal(neo.name!))
}
}
}
}
}
|
mit
|
406f0ab2dcca069914e17cf1c43e0630
| 40.051724 | 99 | 0.49895 | 4.578846 | false | false | false | false |
apple/swift
|
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_class.swift
|
19
|
1689
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
fileprivate class Value<First> {
let first_Value: First
init(first: First) {
self.first_Value = first
}
}
fileprivate class Box {
let value: Int
init(value: Int) {
self.value = value
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// TODO: Prespecialize for Klazz<C> for C a class by initializing C in the
// canonical specialized metadata accessor for Klazz<C>. At that point,
// there should be no call to
// __swift_instantiateConcreteTypeFromMangledName.
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName(
// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z0-9_]+]]LLCyAA3BoxACLLCGMD"
// CHECK: {{%[0-9]+}} = call swiftcc %T4main5Value[[UNIQUE_ID_1]]LLC* @"$s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* swiftself [[METADATA]]
// CHECK-SAME: )
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( Value(first: Box(value: 13)) )
}
doit()
|
apache-2.0
|
47ed930dee6440dd068304f3c7f8754b
| 32.78 | 214 | 0.653049 | 3.211027 | false | false | false | false |
IbrahimZananiri/swifty-traveller
|
Tests/AppTests/ExpediaServiceTests.swift
|
1
|
3968
|
//
// ServiceTests.swift
// AppTests
//
// Created by Ibrahim Z on 10/9/17.
//
import XCTest
import Foundation
import Testing
import HTTP
import Core
@testable import Vapor
@testable import App
// FakeResponder is a fake HTTP client type that will be passes to ExpediaService
// It reads from local json file, builds, and returns a known success Response
class FakeResponder: Responder {
func respond(to request: Request) throws -> Response {
let pwd = Core.workingDirectory()
guard let data = FileManager.default.contents(atPath: "\(pwd)/Tests/AppTests/fake-response.json") else {
throw ResponseError.bytesNotFound
}
return Response(status: .ok, body: data.makeBytes())
}
enum ResponseError: Error {
case bytesNotFound
}
}
class ExpediaServiceTests: TestCase {
let drop = try! Droplet.testable()
fileprivate var anOfferFilter: OfferFilter {
let epoch = Date.init(timeIntervalSince1970: 0)
let epochPlusOneDay = Date(timeIntervalSince1970: 24 * 60 * 60)
let filter = OfferFilter(destinationName: "New York", destinationCity: nil, regionId: nil, minTripStartDate: epoch, maxTripStartDate: epochPlusOneDay, lengthOfStay: nil, minStarRating: nil, maxStarRating: nil, minTotalRate: nil, maxTotalRate: nil, minGuestRating: nil)
return filter
}
func makeURLComponents(with query: String) -> URLComponents {
let url = URL(string: "https://www.google.com?\(query)")!
return URLComponents(url: url, resolvingAgainstBaseURL: false)!
}
func testOfferFilter() throws {
let filter: OfferFilter = self.anOfferFilter
let filterQueryString: String? = filter.queryString
let expectedQueryString: String = "destinationName=New%20York&minTripStartDate=1970-01-01&maxTripStartDate=1970-01-02"
XCTAssertNotNil(filterQueryString)
let components: URLComponents = makeURLComponents(with: expectedQueryString)
XCTAssertNotNil(components)
let expectedComponents: URLComponents = makeURLComponents(with: filterQueryString!)
XCTAssertEqual(components.queryItems!.sorted(by: {$0.name < $1.name}), expectedComponents.queryItems!.sorted(by: {$0.name < $1.name}))
}
func testOfferRequest() throws {
let offerRequest = OfferRequest<HotelOffer>(filter: self.anOfferFilter)
let uri: URI = offerRequest.httpRequest.uri
XCTAssertEqual(uri.scheme, "https")
XCTAssertEqual(uri.port, 443)
XCTAssertEqual(uri.path, "/offers/v2/getOffers")
XCTAssertNotNil(uri.query)
let components: URLComponents = makeURLComponents(with: uri.query!)
let expectedQueryString = "scenario=deal-finder&page=foo&uid=foo&productType=Hotel&destinationName=New%20York&minTripStartDate=1970-01-01&maxTripStartDate=1970-01-02"
let expectedComponents: URLComponents = makeURLComponents(with: expectedQueryString)
XCTAssertEqual(components.queryItems!.sorted(by: {$0.name < $1.name}), expectedComponents.queryItems!.sorted(by: {$0.name < $1.name}))
}
func testExpediaService() throws {
// Initialize an ExpediaService with the fake client
let svc: ExpediaService = ExpediaService(client: FakeResponder())
let offerRequest = OfferRequest<HotelOffer>(filter: self.anOfferFilter)
let envelope: OffersEnvelope<HotelOffer> = try svc.fetchOffersEnvelope(request: offerRequest)
XCTAssertNotNil(envelope.offerInfo)
XCTAssertEqual(envelope.offers?.count, 5)
}
}
// MARK: Manifest
extension ExpediaServiceTests {
/// This is a requirement for XCTest on Linux
/// to function properly.
/// See ./Tests/LinuxMain.swift for examples
static let allTests = [
("testOfferFilter", testOfferFilter),
("testOfferRequest", testOfferRequest),
("testExpediaService", testExpediaService),
]
}
|
mit
|
93685915755bf0fc5adbc8d8f7aabbda
| 39.907216 | 276 | 0.699345 | 4.394241 | false | true | false | false |
ios-archy/Sinaweibo_swift
|
SinaWeibo_swift/SinaWeibo_swift/AppDelegate.swift
|
1
|
1100
|
//
// AppDelegate.swift
// SinaWeibo_swift
//
// Created by yuqi on 16/10/17.
// Copyright © 2016年 archy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultViewController : UIViewController? {
let isLogin = UserAccountViewModel.shareInstance.isLogin
return isLogin ? WelcomeViewController() :UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//设置全局颜色
UITabBar.appearance().tintColor = UIColor.orangeColor()
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
//
//创建Window
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defaultViewController
window?.makeKeyAndVisible()
return true
}
}
|
mit
|
394c44de356e2d2728358a5ab86862c0
| 24.738095 | 127 | 0.681776 | 5.378109 | false | false | false | false |
wenluma/swift
|
stdlib/public/core/Unicode.swift
|
4
|
34833
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
@_fixed_layout
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(Unicode.Scalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with
/// decoded Unicode scalar values.
public protocol UnicodeCodec : Unicode.Encoding {
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
extension Unicode.UTF8 : UnicodeCodec {
/// Creates an instance of the UTF-8 codec.
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inline(__always)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF8.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ].
let value = buffer & 0xff
return (value, 1)
}
var p = ForwardParser()
p._buffer._storage = buffer
p._buffer._bitCount = 32
var i = EmptyCollection<UInt8>().makeIterator()
switch p.parseScalar(from: &i) {
case .valid(let s):
return (
result: UTF8.decode(s).value,
length: UInt8(truncatingIfNeeded: s.count))
case .error(let l):
return (result: nil, length: UInt8(truncatingIfNeeded: l))
case .emptyInput: Builtin.unreachable()
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inline(__always)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._biasedBits
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
return Int(_swift_stdlib_strlen_unsigned(input))
}
// Support parsing C strings as-if they are UTF8 strings.
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CChar>
) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF8")
public typealias UTF8 = Unicode.UTF8
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
extension Unicode.UTF16 : UnicodeCodec {
/// Creates an instance of the UTF-16 codec.
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF16.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._storage
processCodeUnit(UInt16(truncatingIfNeeded: s))
s &>>= 16
if _fastPath(s == 0) { return }
processCodeUnit(UInt16(truncatingIfNeeded: s))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF16")
public typealias UTF16 = Unicode.UTF16
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
extension Unicode.UTF32 : UnicodeCodec {
/// Creates an instance of the UTF-32 codec.
public init() { self = ._swift3Codec }
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `Unicode.Scalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
var parser = ForwardParser()
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF32.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF32")
public typealias UTF32 = Unicode.UTF32
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
@inline(__always)
public func transcode<
Input : IteratorProtocol,
InputEncoding : Unicode.Encoding,
OutputEncoding : Unicode.Encoding
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var p = InputEncoding.ForwardParser()
var hadError = false
loop:
while true {
switch p.parseScalar(from: &input) {
case .valid(let s):
let t = OutputEncoding.transcode(s, from: inputEncoding)
guard _fastPath(t != nil), let s = t else { break }
s.forEach(processCodeUnit)
continue loop
case .emptyInput:
return hadError
case .error:
if _slowPath(stopOnError) { return true }
hadError = true
}
OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit)
}
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(truncatingIfNeeded: x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(truncatingIfNeeded: utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: Unicode.Scalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: Unicode.Scalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: Unicode.Scalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
public static func leadSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xD800 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) &>> (10 as UInt32))
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
public static func trailSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xDC00 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) & (((1 as UInt32) &<< 10) - 1))
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<
Input : IteratorProtocol,
Encoding : Unicode.Encoding
>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where Encoding.CodeUnit == Input.Element {
var utf16Count = 0
var i = input
var d = Encoding.ForwardParser()
// Fast path for ASCII in a UTF8 buffer
if sourceEncoding == Unicode.UTF8.self {
var peek: Encoding.CodeUnit = 0
while let u = i.next() {
peek = u
guard _fastPath(peek < 0x80) else { break }
utf16Count = utf16Count + 1
}
if _fastPath(peek < 0x80) { return (utf16Count, true) }
var d1 = UTF8.ForwardParser()
d1._buffer.append(numericCast(peek))
d = _identityCast(d1, to: Encoding.ForwardParser.self)
}
var utf16BitUnion: CodeUnit = 0
while true {
let s = d.parseScalar(from: &i)
if _fastPath(s._valid != nil), let scalarContent = s._valid {
let utf16 = transcode(scalarContent, from: sourceEncoding)
._unsafelyUnwrappedUnchecked
utf16Count += utf16.count
for x in utf16 { utf16BitUnion |= x }
}
else if let _ = s._error {
guard _fastPath(repairingIllFormedSequences) else { return nil }
utf16Count += 1
utf16BitUnion |= 0xFFFD
}
else {
return (utf16Count, utf16BitUnion < 0x80)
}
}
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension Unicode.Scalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
@_versioned
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
extension UnicodeCodec {
@available(*, unavailable, renamed: "encode(_:into:)")
public static func encode(
_ input: Unicode.Scalar,
output put: (CodeUnit) -> Void
) {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
/// A namespace for Unicode utilities.
public enum Unicode {}
|
mit
|
3413c37367846d8a711d7bdad792e6c0
| 36.745928 | 106 | 0.641324 | 3.95315 | false | false | false | false |
kousun12/RxSwift
|
RxExample/RxExample/Services/Randomizer.swift
|
21
|
6802
|
//
// Randomizer.swift
// RxExample
//
// Created by Krunoslav Zaher on 6/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
typealias NumberSection = HashableSectionModel<String, Int>
let insertItems = true
let deleteItems = true
let moveItems = true
let reloadItems = true
let deleteSections = true
let insertSections = true
let explicitlyMoveSections = true
let reloadSections = true
class Randomizer {
var sections: [NumberSection]
var rng: PseudoRandomGenerator
var unusedItems: [Int]
var unusedSections: [String]
init(rng: PseudoRandomGenerator, sections: [NumberSection]) {
self.rng = rng
self.sections = sections
self.unusedSections = []
self.unusedItems = []
}
func countTotalItemsInSections(sections: [NumberSection]) -> Int {
return sections.reduce(0) { p, s in
return p + s.items.count
}
}
func randomize() {
var nextUnusedSections = [String]()
var nextUnusedItems = [Int]()
let sectionCount = sections.count
let itemCount = countTotalItemsInSections(sections)
let startItemCount = itemCount + unusedItems.count
let startSectionCount = sections.count + unusedSections.count
// insert sections
for section in unusedSections {
let index = rng.get_random() % (sections.count + 1)
if insertSections {
sections.insert(NumberSection(model: section, items: []), atIndex: index)
}
else {
nextUnusedSections.append(section)
}
}
// insert/reload items
for unusedValue in unusedItems {
let sectionIndex = rng.get_random() % sections.count
let section = sections[sectionIndex]
let itemCount = section.items.count
// insert
if rng.get_random() % 2 == 0 {
let itemIndex = rng.get_random() % (itemCount + 1)
if insertItems {
sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex)
}
else {
nextUnusedItems.append(unusedValue)
}
}
// update
else {
if itemCount == 0 {
sections[sectionIndex].items.insert(unusedValue, atIndex: 0)
continue
}
let itemIndex = rng.get_random() % itemCount
if reloadItems {
nextUnusedItems.append(sections[sectionIndex].items.removeAtIndex(itemIndex))
sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex)
}
else {
nextUnusedItems.append(unusedValue)
}
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
let itemActionCount = itemCount / 7
let sectionActionCount = sectionCount / 3
// move items
for _ in 0 ..< itemActionCount {
if self.sections.count == 0 {
continue
}
let sourceSectionIndex = rng.get_random() % self.sections.count
let destinationSectionIndex = rng.get_random() % self.sections.count
let sectionItemCount = sections[sourceSectionIndex].items.count
if sectionItemCount == 0 {
continue
}
let sourceItemIndex = rng.get_random() % sectionItemCount
let nextRandom = rng.get_random()
if moveItems {
let item = sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex)
let targetItemIndex = nextRandom % (self.sections[destinationSectionIndex].items.count + 1)
sections[destinationSectionIndex].items.insert(item, atIndex: targetItemIndex)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// delete items
for _ in 0 ..< itemActionCount {
if self.sections.count == 0 {
continue
}
let sourceSectionIndex = rng.get_random() % self.sections.count
let sectionItemCount = sections[sourceSectionIndex].items.count
if sectionItemCount == 0 {
continue
}
let sourceItemIndex = rng.get_random() % sectionItemCount
if deleteItems {
nextUnusedItems.append(sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex))
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// move sections
for _ in 0 ..< sectionActionCount {
if sections.count == 0 {
continue
}
let sectionIndex = rng.get_random() % sections.count
let targetIndex = rng.get_random() % sections.count
if explicitlyMoveSections {
let section = sections.removeAtIndex(sectionIndex)
sections.insert(section, atIndex: targetIndex)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// delete sections
for _ in 0 ..< sectionActionCount {
if sections.count == 0 {
continue
}
let sectionIndex = rng.get_random() % sections.count
if deleteSections {
let section = sections.removeAtIndex(sectionIndex)
for item in section.items {
nextUnusedItems.append(item)
}
nextUnusedSections.append(section.model)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
unusedSections = nextUnusedSections
unusedItems = nextUnusedItems
}
}
|
mit
|
6cfabcd60061046c846764936f4a2fc7
| 32.348039 | 107 | 0.555572 | 5.43725 | false | false | false | false |
coderwjq/swiftweibo
|
SwiftWeibo/SwiftWeibo/Classes/Compose/PicPicker/PicPickerViewCell.swift
|
1
|
1366
|
//
// PicPickerViewCell.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/9.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
class PicPickerViewCell: UICollectionViewCell {
// MARK:- 控件的属性
@IBOutlet weak var addPhotoBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var removePhotoBtn: UIButton!
// MARK:- 自定义的属性
var image: UIImage? {
didSet {
if image != nil {
// 如果有图片就给imageView设置图片
imageView.image = image
addPhotoBtn.isUserInteractionEnabled = false
removePhotoBtn.isHidden = false
} else {
imageView.image = nil
addPhotoBtn.isUserInteractionEnabled = true
removePhotoBtn.isHidden = true
}
}
}
// MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK:- 事件监听
@IBAction func addPhotoClick() {
NotificationCenter.default.post(name: Notification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
}
@IBAction func removePhotoClick() {
NotificationCenter.default.post(name: Notification.Name(rawValue: PicPickerRemovePhotoNote), object: imageView.image)
}
}
|
apache-2.0
|
2fc53528b5560f804bd15d24be903673
| 26.638298 | 125 | 0.60893 | 4.828996 | false | false | false | false |
mrgerych/Cuckoo
|
Source/stubbing/StubCall.swift
|
3
|
986
|
//
// StubCall.swift
// Cuckoo
//
// Created by Filip Dolnik on 29.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public protocol StubCall {
var method: String { get }
var parametersAsString: String { get }
}
public struct ConcreteStubCall<IN>: StubCall {
public let method: String
public let parameters: IN
public var parametersAsString: String {
let string = String(describing: parameters)
if (string.range(of: ",") != nil && string.hasPrefix("(")) || string == "()" {
return string
} else {
// If only one parameter add brackets and quotes
let wrappedParameter = String(describing: (parameters, 0))
return wrappedParameter.substring(to: wrappedParameter.characters.index(wrappedParameter.endIndex, offsetBy: -4)) + ")"
}
}
public init(method: String, parameters: IN) {
self.method = method
self.parameters = parameters
}
}
|
mit
|
03e6a06fa67c7a7ad1c95bec59c6dbe5
| 28.848485 | 131 | 0.62335 | 4.339207 | false | false | false | false |
drewag/Swiftlier
|
Sources/Swiftlier/Formatting/Data+Base64.swift
|
1
|
2081
|
//
// Data+Base64.swift
// file-sync-services
//
// Created by Andrew J Wagner on 4/10/17.
//
//
import Foundation
extension Data {
static let base64Characters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
static let base64UrlCharacters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
public var base64: String {
return [UInt8](self).base64
}
public var base64ForUrl: String {
return [UInt8](self).base64ForUrl
}
}
extension Array where Element == UInt8 {
public var base64: String {
return self.encode(withCharacters: Data.base64Characters)
}
public var base64ForUrl: String {
return self.encode(withCharacters: Data.base64UrlCharacters)
}
private func encode(withCharacters characters: [Character]) -> String {
var output = ""
var firstByte: UInt8?
var secondByte: UInt8?
var thirdByte: UInt8?
func appendPattern() {
guard let first = firstByte else {
return
}
let second = secondByte ?? 0
let third = thirdByte ?? 0
output.append(characters[Int(first >> 2)])
output.append(characters[Int((first << 6) >> 2 + second >> 4)])
if secondByte == nil {
output.append("=")
}
else {
output.append(characters[Int((second << 4) >> 2 + third >> 6)])
}
if thirdByte == nil {
output.append("=")
}
else {
output.append(characters[Int(third & 63)])
}
}
for byte in self {
guard firstByte != nil else {
firstByte = byte
continue
}
guard secondByte != nil else {
secondByte = byte
continue
}
thirdByte = byte
appendPattern()
firstByte = nil
secondByte = nil
thirdByte = nil
}
appendPattern()
return output
}
}
|
mit
|
2b6c502ad5c0930038dfaeb99ce2ad6f
| 24.072289 | 110 | 0.551177 | 4.740319 | false | false | false | false |
Railsreactor/json-data-sync-swift
|
JDSKit/Core/EntityService.swift
|
1
|
9918
|
//
// EntityService.swift
// JDSKit
//
// Created by Igor Reshetnikov on 12/8/15.
// Copyright © 2015 RailsReactor. All rights reserved.
//
import Foundation
import PromiseKit
import CocoaLumberjack
open class EntityService: CoreService {
open var entityType: ManagedEntity.Type
public required init (entityType: ManagedEntity.Type) {
self.entityType = entityType
}
open class func sharedService<T: ManagedEntity>(_ entityType: T.Type = T.self) -> EntityService {
return AbstractRegistryService.mainRegistryService.entityService(entityType)
}
open func entityGateway() -> GenericEntityGateway? {
return self.localManager.entityGatewayByEntityType(self.entityType)
}
fileprivate func cachedEntity(_ inputQuery: String = "", arguments: [Any]? = nil, sortKeys: [String]? = nil) -> [ManagedEntity] {
let descriptors: [NSSortDescriptor] = sortKeys?.sortDescriptors() ?? [NSSortDescriptor(key: "createDate", ascending: false)]
var query = inputQuery
if !query.isEmpty {
query += " && "
}
query += "isLoaded == true && pendingDelete != true"
do {
if let entitiyGateway = self.entityGateway() {
let entities = try entitiyGateway.fetchEntities(query, arguments: (arguments ?? [Any]()), sortDescriptors: descriptors) as [ManagedEntity]
return entities
}
} catch {
DDLogDebug("Failed to fetch cars: \(error)")
}
return [ManagedEntity]()
}
open func syncEntityInternal(_ query: String = "", arguments: [Any]? = nil, remoteFilters: [NSComparisonPredicate]?=nil, includeRelations: [String]?=nil) -> Promise<Void> {
return self.remoteManager.loadEntities(self.entityType, filters: remoteFilters, include: includeRelations).then(on: .global()) { (input) -> Promise<Void> in
return self.runOnBackgroundContext { () -> Void in
let start = NSDate()
DDLogDebug("Will Insert \(input.count) Entities of type: \(String(describing: self.entityType))" )
if let entityGateway = self.entityGateway() {
let newItems: [ManagedEntity] = try entityGateway.insertEnities(input, isFirstInsert: false) ?? []
DDLogDebug("Did Insert \(newItems.count) Entities of type: \(String(describing: self.entityType)) Time Spent: \(abs(start.timeIntervalSinceNow))" )
} else {
DDLogDebug("No gateway for Entities of type: \(String(describing: self.entityType)). Skipped. Time Spent: \(abs(start.timeIntervalSinceNow))" )
}
}
}
}
open func syncEntityDelta(_ updateDate: Date?) -> Promise<Void> {
return Promise<Void>(value:()).then(on: .global()) { _ -> Promise<Void> in
if self.trySync() {
var predicates: [NSComparisonPredicate]? = nil
if updateDate != nil {
predicates = [NSComparisonPredicate(format: "updated_at_gt == %@", optionals: [updateDate!.toSystemString()])]
}
DDLogDebug("Will download \(self.entityType) Delta From: \(updateDate)")
return self.syncEntityInternal("", arguments: nil, remoteFilters: predicates, includeRelations: nil).always {
self.endSync()
}
} else {
self.waitForSync()
return Promise<Void>(value:())
}
}
}
open func syncEntity(_ query: String = "", arguments: [Any]? = nil, remoteFilters: [NSComparisonPredicate]?=nil, includeRelations: [String]?=nil, includeEntities: [ManagedEntity.Type]?=nil, skipSave: Bool = false) -> Promise<Void> {
var promiseChain = Promise<Void>(value:())
if includeEntities != nil {
for type in includeEntities! {
let includeService = AbstractRegistryService.mainRegistryService.entityService(type)
promiseChain = promiseChain.then(on: .global()) {
return includeService.syncEntity("", arguments: nil, remoteFilters: nil, includeRelations: nil, includeEntities: nil, skipSave: true)
}
}
}
return promiseChain.then(on: .global()) { _ -> Promise<Void> in
if self.trySync() {
return self.syncEntityInternal(query, arguments: arguments, remoteFilters: remoteFilters, includeRelations: includeRelations).then(on: .global()) { () -> Void in
if !skipSave {
self.localManager.saveSyncSafe()
}
}.always {
self.endSync()
}
} else {
self.waitForSync()
return Promise<Void>(value:())
}
}
}
fileprivate func refreshEntity(_ entity: ManagedEntity, includeRelations: [String]?=nil) -> Promise<Void> {
guard let id = entity.id else {
return Promise(error: CoreError.runtimeError(description: "Entity must have an id", cause: nil))
}
let predicate = NSComparisonPredicate(format: "id_eq == \(id)", optionals: nil)
return self.remoteManager.loadEntities(self.entityType, filters: [predicate], include: includeRelations).then(on: .global()) { entities -> Promise<Void> in
return self.runOnBackgroundContext {
if let entity = entities.first {
try self.entityGateway()?.insertEntity(entity)
}
self.localManager.saveSyncSafe()
}
}
}
//MARK: - Other
fileprivate func saveEntity(_ entity: ManagedEntity) -> Promise<ManagedEntity> {
return self.remoteManager.saveEntity(entity).then(on: .global()) { (remoteEntity) -> Promise<Container> in
return self.runOnBackgroundContext { () -> Container in
let result = try self.entityGateway()?.insertEntity(remoteEntity) ?? remoteEntity
self.localManager.saveBackgroundUnsafe()
return result.objectContainer()
}
}.then { (container) -> ManagedEntity in
let entity = try (container.containedObject()! as ManagedEntity)
entity.refresh()
return entity
}
}
fileprivate func deleteEntity(_ entity: ManagedEntity) -> Promise<Void> {
entity.pendingDelete = true
let countainer = entity.objectContainer()
return self.remoteManager.deleteEntity(entity).recover { (error) -> Void in
switch error {
case CoreError.serviceError(_, _):
return
default:
entity.pendingDelete = nil
throw error
}
}.thenInBGContext { () -> Void in
try self.entityGateway()?.deleteEntity(countainer.containedObject()!)
self.localManager.saveBackgroundUnsafe()
}
}
fileprivate func createBlankEntity() -> ManagedEntity {
let dummyClass: DummyManagedEntity.Type = ModelRegistry.sharedRegistry.extractRep(entityType, subclassOf: DummyManagedEntity.self) as! DummyManagedEntity.Type
return dummyClass.init()
}
fileprivate func patchEntity(_ entity: ManagedEntity, applyPatch: (_ entity: ManagedEntity) -> Void ) -> Promise<ManagedEntity> {
let patch: ManagedEntity = self.createBlankEntity()
patch.id = entity.id!
applyPatch(patch)
return self.remoteManager.saveEntity(patch).thenInBGContext { (remoteEntity) -> Container in
let result = try self.entityGateway()?.insertEntity(remoteEntity) ?? remoteEntity
self.localManager.saveBackgroundUnsafe()
return result.objectContainer()
}.then { (container) -> ManagedEntity in
let entity = try (container.containedObject()! as ManagedEntity)
entity.refresh()
return entity
}
}
fileprivate func createOrUpdate(_ entity: ManagedEntity, updateClosure: ((_ entity: ManagedEntity) -> Void)? = nil) -> Promise<ManagedEntity> {
if entity.isTemp() {
if updateClosure != nil {
updateClosure!(entity)
}
return saveEntity(entity)
} else {
return patchEntity(entity, applyPatch: updateClosure! )
}
}
}
open class GenericService<T: ManagedEntity>: EntityService {
public required init() {
super.init(entityType: T.self)
}
public required init(entityType: ManagedEntity.Type) {
fatalError("init(entityType:) has not been implemented")
}
open class func sharedService() -> GenericService<T> {
return AbstractRegistryService.mainRegistryService.entityService()
}
open func cachedEntity(_ query: String = "", arguments: [Any]? = nil, sortKeys: [String]?=nil) -> [T] {
return super.cachedEntity(query, arguments: arguments, sortKeys: sortKeys) as! [T]
}
open func createOrUpdate(_ entity: T, updateClosure: ((_ entity: T) -> Void)? = nil) -> Promise<T> {
return super.createOrUpdate(entity, updateClosure: updateClosure != nil ? { updateClosure!($0 as! T) } : nil).then { $0 as! T }
}
open func refreshEntity(_ entity: T, includeRelations: [String]?=nil) -> Promise<Void> {
return super.refreshEntity(entity, includeRelations: includeRelations)
}
open func deleteEntity(_ entity: T) -> Promise<Void> {
return super.deleteEntity(entity)
}
open func createBlankEntity() -> T {
return super.createBlankEntity() as! T
}
}
|
mit
|
fb3cdb56c2ceb77d0cfa2fc07e74df9b
| 40.493724 | 236 | 0.594535 | 4.821099 | false | false | false | false |
mthud/MorphingLabel
|
CharacterDiffResult.swift
|
1
|
1453
|
//
// CharacterDiffResult.swift
// https://github.com/mthud/MorphingLabel
//
import Foundation
public enum CharacterDiffResult: CustomDebugStringConvertible, Equatable {
case same
case add
case delete
case move(offset: Int)
case moveAndAdd(offset: Int)
case replace
public var debugDescription: String {
switch self {
case .same:
return "The character is unchanged."
case .add:
return "A new character is ADDED."
case .delete:
return "The character is DELETED."
case .move(let offset):
return "The character is MOVED to \(offset)."
case .moveAndAdd(let offset):
return "The character is MOVED to \(offset) and a new character is ADDED."
case .replace:
return "The character is REPLACED with a new character."
}
}
}
public func == (lhs: CharacterDiffResult, rhs: CharacterDiffResult) -> Bool
{
switch (lhs, rhs) {
case (.move(let offset0), .move(let offset1)):
return offset0 == offset1
case (.moveAndAdd(let offset0), .moveAndAdd(let offset1)):
return offset0 == offset1
case (.add, .add):
return true
case (.delete, .delete):
return true
case (.replace, .replace):
return true
case (.same, .same):
return true
default: return false
}
}
|
mit
|
0b017fdd4feafdee37d95d8bdfa0c93c
| 24.051724 | 86 | 0.582932 | 4.376506 | false | false | false | false |
dneubaue/OFXParser
|
OFXParser.swift
|
1
|
5207
|
//
// OFXParser.swift
// Wallet
//
// Created by Duff Neubauer on 10/18/15.
// Copyright © 2015 Duff Neubauer. All rights reserved.
//
import Foundation
//
// OFX Tags
//
private struct OFXTags {
struct BankInfo {
static let Base = "FI"
static let BankOrg = "ORG"
static let BankOrgID = "FID"
}
struct StatementResponse {
static let Base = "STMTRS"
static let Currency = "CURDEF"
}
struct AccountInfo {
static let AccountInfo = "BANKACCTFROM"
static let RoutingNumber = "BANKID"
static let AccountNumber = "ACCTID"
static let AccountType = "ACCTTYPE"
}
struct BankTransactions {
static let Base = "BANKTRANLIST"
static let Transaction = "STMTTRN"
static let Type = "TRNTYPE"
static let DatePosted = "DTPOSTED"
static let Amount = "TRNAMT"
static let UniqueID = "FITID"
static let Name = "NAME"
static let Memo = "MEMO"
static let CheckNumber = "CHECKNUM"
}
}
//
// OFXParser
//
struct OFXParser {
let contents: String
enum BankAccountInfo {
case Org, ID, Currency, RoutingNumber, AccountNumber, AccountType
}
enum TransactionInfo {
case TransactionType, DatePosted, Amount, UniqueID, CheckNum, Name, Memo
}
//
// MARK: Lifecycle
//
init?(ofxFile: NSURL) {
// Check file exists
if !NSFileManager.defaultManager().fileExistsAtPath(ofxFile.path!) {
return nil
}
do {
self.contents = try String(contentsOfURL: ofxFile, encoding: NSASCIIStringEncoding)
} catch {
return nil
}
}
//
// MARK: Public API
//
func bankInformation() -> [BankAccountInfo: String]? {
guard let bankInfo = self.blocksWithTag("FI", inString: self.contents)?.first,
let bankOrg = self.valueOfTag("ORG", inString: bankInfo),
let bankID = self.valueOfTag("FID", inString: bankInfo),
let statement = self.blocksWithTag("STMTRS", inString: self.contents)?.first,
let currency = self.valueOfTag("CURDEF", inString: statement),
let accountInfo = self.blocksWithTag("BANKACCTFROM", inString: statement)?.first,
let routingNum = self.valueOfTag("BANKID", inString: accountInfo),
let accountNum = self.valueOfTag("ACCTID", inString: accountInfo),
let accountType = self.valueOfTag("ACCTTYPE", inString: accountInfo) else { return nil }
return [
BankAccountInfo.Org: bankOrg,
BankAccountInfo.ID: bankID,
BankAccountInfo.Currency: currency,
BankAccountInfo.RoutingNumber: routingNum,
BankAccountInfo.AccountNumber: accountNum,
BankAccountInfo.AccountType: accountType
]
}
func bankTransactions() -> [[TransactionInfo: String]]? {
guard let transactionsList = self.blocksWithTag("BANKTRANLIST", inString: self.contents)?.first,
let transactions = self.blocksWithTag("STMTTRN", inString: transactionsList) else { return nil }
return transactions.map {
var transaction: [TransactionInfo: String] = [:]
if let type = self.valueOfTag("TRNTYPE", inString: $0) {
transaction[TransactionInfo.TransactionType] = type
}
if let date = self.valueOfTag("DTPOSTED", inString: $0) {
transaction[TransactionInfo.DatePosted] = date
}
if let amount = self.valueOfTag("TRNAMT", inString: $0) {
transaction[TransactionInfo.Amount] = amount
}
if let ID = self.valueOfTag("FITID", inString: $0) {
transaction[TransactionInfo.UniqueID] = ID
}
if let name = self.valueOfTag("NAME", inString: $0) {
transaction[TransactionInfo.Name] = name
}
if let memo = self.valueOfTag("MEMO", inString: $0) {
transaction[TransactionInfo.Memo] = memo
}
if let checkNum = self.valueOfTag("CHECKNUM", inString: $0) {
transaction[TransactionInfo.CheckNum] = checkNum
}
return transaction
}
}
//
// MARK: Private Helper Functions
//
func blocksWithTag(tag:String, inString string:String) -> [String]? {
do {
let pattern = "<\(tag)>(.+?)</\(tag)>"
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
let range = NSMakeRange(0, string.characters.count)
let matches = regex.matchesInString(string, options: [], range: range)
return matches.map {
return (string as NSString).substringWithRange($0.range)
}
} catch {
return nil
}
}
func valueOfTag(tag:String, inString string:String) -> String? {
guard let matchRange = string.rangeOfString("<\(tag)>.+", options: .RegularExpressionSearch, range: nil, locale: nil) else { return nil }
let tagLength = "<\(tag)>".characters.count
let stringRange = Range(start: matchRange.startIndex.advancedBy(tagLength), end: matchRange.endIndex)
return string.substringWithRange(stringRange)
}
}
|
mit
|
35c8ac0c3371666b2634d9793e6028a3
| 29.629412 | 142 | 0.621014 | 4.083137 | false | false | false | false |
kmcgill88/KMKeys-iOS
|
Example/KMKeys/ViewController.swift
|
1
|
4479
|
/*
Copyright (c) 2017-2018 Kevin McGill <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import KMKeys
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBAction func pressed(_ sender: UIButton) {
// Short hand, default settings
//
KMKeys.show() { (text:String?) in
self.label.text = text
}
}
@IBAction func pressedCusomtized(_ sender: Any) {
let keys = KMKeys()
// Change Default speed (0.15)
//
keys.animationSpeed = 0.05
// Customize the text field
//
keys.textField.textAlignment = .center
keys.textField.placeholder = "Placeholder Text Here"
keys.textField.font = UIFont(name: "American Typewriter", size: 16.0)!
keys.textField.placeholderColor = UIColor.init(white: 255/255, alpha: 0.75)
keys.textField.backgroundColor = .brown
keys.textField.textColor = .white
keys.textField.tintColor = .white
keys.textField.keyboardType = .decimalPad
keys.textField.keyboardAppearance = .dark
// Customize the toolbar
//
keys.toolbar.barTintColor = .brown
// KMKeyBarButtonItemType.flexibleSpace, .cancel, .done
// Mostly normal buttons, except can set custom titles
//
let flexibleSpace = KMKeyBarButtonItem.flexibleSpace() //<-- Shortcut helper
let cancelBarButton = KMKeyBarButtonItem(title: "Never Mind", style: .plain, action: .cancel, kmKeys: keys)
// let cancelBarButton = KMKeyBarButtonItem.cancel() //<-- Shortcut helper, if custom name not needed
let doneBarButton = KMKeyBarButtonItem.done() //<-- Shortcut helper, if custom name not needed
// let doneBarButton = KMKeyBarButtonItem(title: "Fire!!!", style: .done, action: .done, kmKeys: keys)
// KMKeyBarButtonItemType.textInput
// When you want a toolbar button's title to append to the textField
//
let plusButton = KMKeyBarButtonItem(title: "+", style: UIBarButtonItemStyle.plain, action: KMKeyBarButtonItemType.textInput, kmKeys: keys)
let minusButton = KMKeyBarButtonItem(title: "-", style: .plain, action: .textInput, kmKeys: keys)
let commaButton = KMKeyBarButtonItem(title: ",", style: .plain, action: .textInput, kmKeys: keys)
// KMKeyBarButtonItemType.action
// When you want a button to do
let actionBarButton = KMKeyBarButtonItem(title: "Custom Action", style: .plain, action: KMKeyBarButtonItemType.action, kmKeys: keys, actionHandler: { (_ kmKeys:KMKeys?) in
// Do your custom logic here, in the actionHandler.
//
if let keys = kmKeys {
keys.textField.text = "KMKeys!!!!"
}
})
let fixedSpace = KMKeyBarButtonItem.fixedSpace() //<-- Shortcut helper, by default size is 2% of window width or 5 if window is nil
keys.setToolbarItems(items: [fixedSpace, cancelBarButton, flexibleSpace, plusButton, commaButton, minusButton, actionBarButton, flexibleSpace, doneBarButton, fixedSpace])
keys.setToolbarItemsTintColor(color: .white)
keys.setToolbarItemsFont(font: UIFont(name: "American Typewriter", size: 16.0)!)
keys.show() { (text:String?) in
self.label.text = text
}
}
}
|
mit
|
e876fe029a9f1343856d349e24f78a6c
| 43.79 | 179 | 0.669346 | 4.665625 | false | false | false | false |
DevAndArtist/RxContainer
|
Sources/TransitionContext.swift
|
1
|
1957
|
//
// TransitionContext.swift
// RxContainer
//
// Created by Adrian Zubarev on 13.06.17.
// Copyright © 2017 RxSwiftCommunity. All rights reserved.
//
import UIKit
extension Transition {
///
public struct Context {
//==========-----------------------------==========//
//=====----- Private/Internal properties -----=====//
//==========-----------------------------==========//
///
private let fromViewController: UIViewController
///
private let toViewController: UIViewController
//==========------------------------==========//
//=====----- Open/Public properties -----=====//
//==========------------------------==========//
///
public let kind: Kind
///
public let containerView: UIView
///
public let isAnimated: Bool
///
public let isInteractive: Bool
//==========-------------==========//
//=====----- Initializer -----=====//
//==========-------------==========//
///
init(kind: Kind,
containerView: UIView,
fromViewController: UIViewController,
toViewController: UIViewController,
option: ContainerViewController.Option) {
// Initialize all properties neede for the transition
self.kind = kind
self.containerView = containerView
self.fromViewController = fromViewController
self.toViewController = toViewController
self.isAnimated = option.isAnimated
self.isInteractive = option.isInteractive
}
}
}
extension Transition.Context {
///
public func viewController(forKey key: Key) -> UIViewController {
switch key {
case .from:
return fromViewController
case .to:
return toViewController
}
}
///
public func view(forKey key: Key) -> UIView {
return viewController(forKey: key).view
}
}
extension Transition.Context {
///
public enum Key { case from, to }
///
public enum Kind { case push, pop }
}
|
mit
|
81397817491a6d84f05b5049b65fd697
| 22.011765 | 67 | 0.531697 | 5.315217 | false | false | false | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Challenge3.playgroundpage/Sources/SetUp.swift
|
1
|
3915
|
//
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
//let world = GridWorld(columns: 7, rows: 5)
let world = loadGridWorld(named: "9.7")
let actor = Actor()
public var numberOfGems = 0
public func playgroundPrologue() {
// placeBlocks()
placeRandomPlaceholderGems()
placeSwitches()
placePortals()
world.place(actor, facing: north, at: Coordinate(column: 0, row: 0))
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomGems()
}
//// ----
world.successCriteria = .count(collectedGems: numberOfGems, openSwitches: numberOfGems)
}
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeRandomPlaceholderGems() {
let itemCoords = [
Coordinate(column: 0, row: 4),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 4),
Coordinate(column: 2, row: 3),
Coordinate(column: 2, row: 2),
]
let gem = Gem()
for coord in itemCoords {
world.place(RandomNode(resembling:gem), at: coord)
}
}
func placePortals() {
world.place(Portal(color: .green), between: Coordinate(column: 1, row: 2), and: Coordinate(column: 5, row: 2))
}
func realizeRandomGems() {
let itemCoords = [
Coordinate(column: 0, row: 4),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 4),
Coordinate(column: 2, row: 3),
Coordinate(column: 2, row: 2),
]
for coor in itemCoords {
if arc4random_uniform(6) % 2 == 0 {
world.placeGems(at: [coor])
numberOfGems += 1
}
}
}
func placeSwitches() {
let dzCoords = [
Coordinate(column: 4, row: 4),
Coordinate(column: 4, row: 3),
Coordinate(column: 4, row: 2),
Coordinate(column: 5, row: 4),
Coordinate(column: 6, row: 4),
Coordinate(column: 6, row: 3),
Coordinate(column: 6, row: 2),
]
world.place(nodeOfType: Switch.self, at: dzCoords)
}
func placeBlocks() {
let obstacles = [
Coordinate(column: 1, row: 3),
Coordinate(column: 5, row: 3),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 3),
Coordinate(column: 3, row: 2),
Coordinate(column: 3, row: 1),
Coordinate(column: 2, row: 1),
Coordinate(column: 4, row: 1),
]
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
world.placeBlocks(at: world.coordinates(inColumns: [0,2,4,6], intersectingRows: [2,3,4]))
world.placeBlocks(at: world.coordinates(inColumns: [1,5], intersectingRows: [2,4]))
world.place(Stair(), facing: south, at: Coordinate(column: 0, row: 1))
world.place(Stair(), facing: south, at: Coordinate(column: 6, row: 1))
}
|
mit
|
7833f415821bf4f2427bb8f852d193c5
| 30.829268 | 114 | 0.509068 | 4.250814 | false | false | false | false |
benlangmuir/swift
|
test/Sema/diag_unowned_immediate_deallocation.swift
|
7
|
29846
|
// RUN: %target-typecheck-verify-swift -module-name ModuleName
protocol ClassProtocol : class {
init()
init?(failable: Void)
init(throwing: Void) throws
}
class C : ClassProtocol {
required init() {}
required init?(failable: Void) {}
required init(throwing: Void) throws {}
}
class D : C {}
func testWeakVariableBindingDiag() throws {
weak var c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c2: C? = ModuleName.C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
// expected-note@-3 {{'c2' declared here}}
c2 = C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c3: C? = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c3' declared here}}
// expected-note@-3 {{'c3' declared here}}
c3 = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c4 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c4' declared here}}
// expected-note@-3 {{'c4' declared here}}
c4 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c5: C? = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c5' declared here}}
// expected-note@-3 {{'c5' declared here}}
c5 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c6: C? = D(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c6' declared here}}
// expected-note@-3 {{'c6' declared here}}
c6 = D(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c7' declared here}}
// expected-note@-3 {{'c7' declared here}}
c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c8: C? = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c8' declared here}}
// expected-note@-3 {{'c8' declared here}}
c8 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c9: C? = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c9' declared here}}
// expected-note@-3 {{'c9' declared here}}
c9 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c10' declared here}}
// expected-note@-3 {{'c10' declared here}}
c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c11: C? = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c11' declared here}}
// expected-note@-3 {{'c11' declared here}}
c11 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c12: C? = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c12' declared here}}
// expected-note@-3 {{'c12' declared here}}
c12 = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c13 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c13' declared here}}
// expected-note@-3 {{'c13' declared here}}
c13 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c14: C? = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c14' declared here}}
// expected-note@-3 {{'c14' declared here}}
c14 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c15: C? = try? D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c15' declared here}}
// expected-note@-3 {{'c15' declared here}}
c15 = try? D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6; _ = c7; _ = c8; _ = c9; _ = c10; _ = c11; _ = c12; _ = c13; _ = c14; _ = c15
}
func testUnownedVariableBindingDiag() throws {
unowned(unsafe) var c = C() // expected-warning {{instance will be immediately deallocated because variable 'c' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c' declared here}}
// expected-note@-3 {{'c' declared here}}
c = C() // expected-warning {{instance will be immediately deallocated because variable 'c' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c2: C = ModuleName.C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
// expected-note@-3 {{'c2' declared here}}
c2 = C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c3: C = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c3' declared here}}
// expected-note@-3 {{'c3' declared here}}
c3 = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c4 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c4' declared here}}
// expected-note@-3 {{'c4' declared here}}
c4 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c5: C = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c5' declared here}}
// expected-note@-3 {{'c5' declared here}}
c5 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c6: C = D(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c6' declared here}}
// expected-note@-3 {{'c6' declared here}}
c6 = D(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c7' declared here}}
// expected-note@-3 {{'c7' declared here}}
c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c8: C = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c8' declared here}}
// expected-note@-3 {{'c8' declared here}}
c8 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c9: C = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c9' declared here}}
// expected-note@-3 {{'c9' declared here}}
c9 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c10' declared here}}
// expected-note@-3 {{'c10' declared here}}
c10 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c11: C = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c11' declared here}}
// expected-note@-3 {{'c11' declared here}}
c11 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c12: C = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c12' declared here}}
// expected-note@-3 {{'c12' declared here}}
c12 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c13 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c13' declared here}}
// expected-note@-3 {{'c13' declared here}}
c13 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c14: C = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c14' declared here}}
// expected-note@-3 {{'c14' declared here}}
c14 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c15: C = (try? D(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c15' declared here}}
// expected-note@-3 {{'c15' declared here}}
c15 = (try? D(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
_ = c; _ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6; _ = c7; _ = c8; _ = c9; _ = c10; _ = c11; _ = c12; _ = c13; _ = c14; _ = c15
}
func testMultipleBindingDiag() {
weak var c1 = C(), c2: C? = C(), c3: C? = D()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c1' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c2' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c3' declared here}}
unowned let c4 = C(), c5: C = C(), c6: C = D()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c4' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c5' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c6' declared here}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6
}
func testTupleAndParenBinding() throws {
weak var ((c1), c2, c3): (C?, C?, C?) = (C() as C, (D()), try D(throwing: ()))
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c1' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c2' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c3' declared here}}
unowned let ((c4), c5, c6): (C, C, C) = (C() as C, (D()), try D(throwing: ()))
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c4' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c5' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c6' declared here}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6
}
func testInitializationThroughClassArchetypeDiag<T : ClassProtocol>(_ t: T, _ p: ClassProtocol) throws {
weak var t1: T? = T() // expected-warning {{instance will be immediately deallocated because variable 't1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t1' declared here}}
weak var t2: ClassProtocol? = T(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 't2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t2' declared here}}
unowned let t3 = try type(of: t).init(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 't3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t3' declared here}}
unowned(unsafe) let t4 = type(of: p).init() // expected-warning {{instance will be immediately deallocated because variable 't4' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t4' declared here}}
let optionalTType: T.Type? = T.self
let optionalPType: ClassProtocol.Type? = type(of: p)
weak var t5 = optionalTType?.init(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 't5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t5' declared here}}
unowned(unsafe) let t6 = try (optionalPType?.init(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 't6' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t6' declared here}}
_ = t1; _ = t2; _ = t3; _ = t4; _ = t5; _ = t6
}
weak var topLevelC = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'topLevelC' declared here}}
// expected-note@-3 {{'topLevelC' declared here}}
topLevelC = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var topLevelC1 = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'topLevelC1' declared here}}
// expected-note@-3 {{'topLevelC1' declared here}}
topLevelC1 = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
struct S {
weak var c: C? // expected-note {{'c' declared here}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
mutating func foo() {
c = D() // expected-warning {{instance will be immediately deallocated because property 'c' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
c1 = D() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
}
}
class C1 {
weak var c: C? // expected-note {{'c' declared here}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
func foo() {
c = D() // expected-warning {{instance will be immediately deallocated because property 'c' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
c1 = D() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
}
}
func testInitializationThroughMetaclassDiag(_ t: C.Type) {
weak var c1: C? = t.init() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
let optionalCType: C.Type? = t
weak var c2 = optionalCType?.init(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
_ = c1; _ = c2
}
func testInitializationThroughTupleElementDiag() {
unowned var c1 = ((C() as C, C() as C) as (C, C)).0 // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = ((C() as C, C() as C) as (C, C)).0 // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned let (c2, c3) = ((C() as C, C()) as (C, C), 5).0
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c2' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c3' declared here}}
_ = c1; _ = c2; _ = c3
}
class E<T> {}
func testGenericWeakClassDiag() {
weak var e = E<String>()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'e' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'e' declared here}}
_ = e
}
// The diagnostic doesn't currently support tuple shuffles.
func testDontDiagnoseThroughTupleShuffles() {
unowned let (c1, (c2, c3)): (c: C, (b: C, a: C)) = ((a: D(), b: C()), c: D())
// expected-warning@-1 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
// expected-warning@-2 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
unowned let c4 = ((a: C(), b: C()) as (b: C, a: C)).0
// expected-warning@-1 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
_ = c1; _ = c2; _ = c3; _ = c4
}
extension Optional {
init(dontDiagnoseOnThis: Void) {
self = nil
}
}
func testDontDiagnoseOnUnrelatedInitializer() {
weak var c = C?(dontDiagnoseOnThis: ())
unowned let c1 = C?(dontDiagnoseOnThis: ())!
_ = c; _ = c1
}
class F {
var c: C?
func makeC() -> C { return C() }
}
func testDontDiagnoseThroughMembers() {
weak var c1 = F().c
weak var c2 = F().makeC()
_ = c1; _ = c2
}
func testDontDiagnoseOnStrongVariable() {
var c1 = C()
c1 = C()
_ = c1
}
func testDontDiagnoseThroughImmediatelyEvaluatedClosure() {
weak var c1 = { C() }()
unowned let c2 = { C() }()
_ = c1; _ = c2
}
|
apache-2.0
|
c21388e2c998fc2ed77a6af4ead3d190
| 59.173387 | 175 | 0.698787 | 4.008327 | false | false | false | false |
mshhmzh/firefox-ios
|
Client/Frontend/Browser/SessionData.swift
|
4
|
1890
|
/* 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 Shared
class SessionData: NSObject, NSCoding {
let currentPage: Int
let urls: [NSURL]
let lastUsedTime: Timestamp
var jsonDictionary: [String: AnyObject] {
return [
"currentPage": String(self.currentPage),
"lastUsedTime": String(self.lastUsedTime),
"urls": urls.map { $0.absoluteString }
]
}
/**
Creates a new SessionData object representing a serialized tab.
- parameter currentPage: The active page index. Must be in the range of (-N, 0],
where 1-N is the first page in history, and 0 is the last.
- parameter urls: The sequence of URLs in this tab's session history.
- parameter lastUsedTime: The last time this tab was modified.
**/
init(currentPage: Int, urls: [NSURL], lastUsedTime: Timestamp) {
self.currentPage = currentPage
self.urls = urls
self.lastUsedTime = lastUsedTime
assert(urls.count > 0, "Session has at least one entry")
assert(currentPage > -urls.count && currentPage <= 0, "Session index is valid")
}
required init?(coder: NSCoder) {
self.currentPage = coder.decodeObjectForKey("currentPage") as? Int ?? 0
self.urls = coder.decodeObjectForKey("urls") as? [NSURL] ?? []
self.lastUsedTime = UInt64(coder.decodeInt64ForKey("lastUsedTime")) ?? NSDate.now()
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(currentPage, forKey: "currentPage")
coder.encodeObject(urls, forKey: "urls")
coder.encodeInt64(Int64(lastUsedTime), forKey: "lastUsedTime")
}
}
|
mpl-2.0
|
c901b182c2d0c3f3b61eb9be4d519db4
| 36.82 | 92 | 0.636508 | 4.375 | false | false | false | false |
Huralnyk/rxswift
|
ForwardDelegates/ForwardDelegates/ViewController.swift
|
1
|
1455
|
//
// ViewController.swift
// ForwardDelegates
//
// Created by aleksey on 9/12/17.
// Copyright © 2017 Oleksii Huralnyk. All rights reserved.
//
import UIKit
import RxSwift
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let model = Model()
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Contributor>>()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.configureCell = { _, tableView, indexPath, contributor in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.imageView?.image = contributor.image
cell.textLabel?.text = contributor.name
cell.detailTextLabel?.text = contributor.gitHubID
return cell
}
dataSource.titleForHeaderInSection = { data, section in
data.sectionModels[section].model
}
model.data
.bind(to: tableView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
tableView.rx.setDelegate(self).addDisposableTo(disposeBag)
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(arc4random_uniform(96) + 32)
}
}
|
mit
|
8f09c871b6b3269e03296378272a0786
| 28.08 | 94 | 0.657497 | 5.230216 | false | false | false | false |
takasek/konjac
|
Konjac/Konjac/PhrasesViewController.swift
|
1
|
4188
|
//
// PhrasesViewController.swift
// Konjac
//
// Created by 高松幸平 on 2017/03/04.
// Copyright © 2017年 trySwiftHackathon. All rights reserved.
//
import UIKit
class PhrasesViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var segmentControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "PhraseTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
KonjacFirebase.sharedInstance.configureDatabase()
KonjacFirebase.sharedInstance.addObserveChanges { (konjacModels) in
self.tableView.reloadData()
print(konjacModels)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let selectedRow = self.tableView.indexPathForSelectedRow{
self.tableView.deselectRow(at: selectedRow, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addButtonTap(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "EditViewStoryboard", bundle: Bundle.main)
let viewController = storyboard.instantiateInitialViewController() as! EditViewController
navigationController?.pushViewController(viewController, 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.
}
*/
func modelForIndexPath(indexPath: IndexPath) -> KonjacModel? {
let arr = self.filteredModelArray()
if indexPath.row < 0 || indexPath.row >= arr.count {
return nil
}
return arr[indexPath.row]
}
func filteredModelArray() -> [KonjacModel] {
let arr = KonjacFirebase.sharedInstance.konjacSnaps.filter { model in
model.english != nil
}
var d: [String: KonjacModel] = [:]
for m in arr {
if let e = m.english {
d[e] = m
}
}
return Array(d.values)
}
}
extension Array where Element : Equatable {
var unique: [Element] {
var uniqueValues: [Element] = []
forEach { item in
if !uniqueValues.contains(item) {
uniqueValues += [item]
}
}
return uniqueValues
}
}
extension PhrasesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "RikoModalViewStoryboard", bundle: Bundle.main)
let riko = storyboard.instantiateInitialViewController() as! RikoModalViewController
guard let model = self.modelForIndexPath(indexPath: indexPath) else { return }
riko.engPhrase = model.english
riko.jpnPhrase = model.japanese
let rootViewController = UIApplication.shared.delegate?.window!?.rootViewController
rootViewController!.modalPresentationStyle = UIModalPresentationStyle.currentContext
present(riko, animated: true)
}
}
extension PhrasesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredModelArray().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let model = self.modelForIndexPath(indexPath: indexPath) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PhraseTableViewCell
cell.mainPhrase.text = model.english
cell.subPhrase.text = model.japanese
return cell
}
}
|
mit
|
a311bcd9ebb9b4a1d150b889d99f5988
| 33.808333 | 110 | 0.66938 | 5.112607 | false | false | false | false |
omarojo/MyC4FW
|
Pods/C4/C4/Core/Transform.swift
|
2
|
11556
|
// Copyright © 2014 C4
//
// 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 Accelerate
import CoreGraphics
import QuartzCore
/// A structure for holding a transform matrix.
///
/// Transform can translate, rotate, scale.
public struct Transform: Equatable {
var matrix = [Double](repeating: 0, count: 16)
public subscript(row: Int, col: Int) -> Double {
get {
assert(row >= 0 && row < 4, "Row index out of bounds")
assert(col >= 0 && col < 4, "Column index out of bounds")
return matrix[row + col * 4]
}
set {
assert(row >= 0 && row < 4, "Row index out of bounds")
assert(col >= 0 && col < 4, "Column index out of bounds")
matrix[row + col * 4] = newValue
}
}
/// Initializes a Transform. Defaults to an identity transform.
public init() {
self[0, 0] = 1
self[1, 1] = 1
self[2, 2] = 1
self[3, 3] = 1
}
/// Creates a new transform from a `CGAffineTransform` structure.
/// - parameter t: A `CGAffineTransform` structure.
public init(_ t: CGAffineTransform) {
self.init()
self[0, 0] = Double(t.a)
self[0, 1] = Double(t.b)
self[1, 0] = Double(t.c)
self[1, 1] = Double(t.d)
self[0, 3] = Double(t.tx)
self[1, 3] = Double(t.ty)
}
/// Creates a new transform from a `CATransform3D` structure.
/// - parameter t: A `CATransform3D` structure.
public init(_ t: CATransform3D) {
self[0, 0] = Double(t.m11)
self[0, 1] = Double(t.m12)
self[0, 2] = Double(t.m13)
self[0, 3] = Double(t.m14)
self[1, 0] = Double(t.m21)
self[1, 1] = Double(t.m22)
self[1, 2] = Double(t.m23)
self[1, 3] = Double(t.m24)
self[2, 0] = Double(t.m31)
self[2, 1] = Double(t.m32)
self[2, 2] = Double(t.m33)
self[2, 3] = Double(t.m34)
self[3, 0] = Double(t.m41)
self[3, 1] = Double(t.m42)
self[3, 2] = Double(t.m43)
self[3, 3] = Double(t.m44)
}
/// Returns `true` if transform is affine, otherwise `false`.
public func isAffine() -> Bool {
return self[3, 0] == 0.0 && self[3, 1] == 0.0 && self[3, 2] == 0.0 && self[3, 3] == 1.0
}
/// The translation component of the tranform.
/// - returns: A `Vector` that represents the translation of the transform, where x = [0,3], y = [1,3]
public var translation: Vector {
get {
return Vector(x: self[3, 0], y: self[3, 1])
}
set {
self[3, 0] = newValue.x
self[3, 1] = newValue.y
}
}
/// Creates a transform that represents a translation in 2d (x,y)
/// ````
/// let v = Vector(x: 1, y: 1)
/// let t = Transform.makeTranslation(v)
/// ````
/// - parameter translation: A `Vector` that represents the translation to apply.
/// - returns: A `Transform` that can be used to apply a translation to a receiver.
public static func makeTranslation(_ translation: Vector) -> Transform {
var t = Transform()
t[3, 0] = translation.x
t[3, 1] = translation.y
return t
}
/// Creates a transform that represents a scale in 3d (x, y, z). The `z` component is optional.
/// ````
/// let t = Transform.makeScale(2.0, 2.0)
/// ````
/// - parameter sx: The amount to scale in the `x` axis
/// - parameter sy: The amount to scale in the `y` axis
/// - parameter sz: The amount to scale in the `z` axis
/// - returns: A `Transform` that can be used to scale a receiver.
public static func makeScale(_ sx: Double, _ sy: Double, _ sz: Double = 1) -> Transform {
var t = Transform()
t[0, 0] = sx
t[1, 1] = sy
t[2, 2] = sz
return t
}
/// Creates a transform that represents a rotation. The `axis` component is optional.
/// ````
/// let t = Transform.makeRotation(M_PI)
/// ````
/// - parameter angle: The angle, in radians, to rotate
/// - parameter axis: The axis around which to rotate, defaults to the z axis {0,0,1}
/// - returns: A `Transform` that can be used to rotate a receiver.
public static func makeRotation(_ angle: Double, axis: Vector = Vector(x: 0, y: 0, z : 1)) -> Transform {
if axis.isZero() {
return Transform()
}
let unitAxis = axis.unitVector()!
let ux = unitAxis.x
let uy = unitAxis.y
let uz = unitAxis.z
let ca = cos(angle)
let sa = sin(angle)
var t = Transform()
t[0, 0] = ux * ux * (1 - ca) + ca
t[0, 1] = ux * uy * (1 - ca) - uz * sa
t[0, 2] = ux * uz * (1 - ca) + uy * sa
t[1, 0] = uy * ux * (1 - ca) + uz * sa
t[1, 1] = uy * uy * (1 - ca) + ca
t[1, 2] = uy * uz * (1 - ca) - ux * sa
t[2, 0] = uz * ux * (1 - ca) - uy * sa
t[2, 1] = uz * uy * (1 - ca) + ux * sa
t[2, 2] = uz * uz * (1 - ca) + ca
return t
}
/// Applies a translation to the receiver.
/// ````
/// let v = Vector(x: 1, y: 1)
/// let t = Transform()
/// t.translate(v)
/// ````
/// - parameter translation: A `Vector` that represents the translation to apply.
public mutating func translate(_ translation: Vector) {
let t = Transform.makeTranslation(translation)
self = concat(self, t2: t)
}
/// Applies a scale to the receiver. The `z` variable is optional.
/// ````
/// let t = Transform()
/// t.scale(2.0, 2.0)
/// ````
/// - parameter sx: The amount to scale in the `x` axis
/// - parameter sy: The amount to scale in the `y` axis
/// - parameter sz: The amount to scale in the `z` axis
public mutating func scale(_ sx: Double, _ sy: Double, _ sz: Double = 1) {
let s = Transform.makeScale(sx, sy, sz)
self = concat(self, t2: s)
}
/// Applies a rotation. The `axis` component is optional.
/// ````
/// let t = Transform()
/// t.rotate(M_PI)
/// ````
/// - parameter angle: The angle, in radians, to rotate
/// - parameter axis: The axis around which to rotate, defaults to the z axis {0,0,1}
public mutating func rotate(_ angle: Double, axis: Vector = Vector(x: 0, y: 0, z: 1)) {
let r = Transform.makeRotation(angle, axis: axis)
self = concat(self, t2: r)
}
/// The CGAffineTransform version of the receiver.
/// - returns: A `CGAffineTransform` that is equivalent to the receiver.
public var affineTransform: CGAffineTransform {
return CGAffineTransform(
a: CGFloat(self[0, 0]),
b: CGFloat(self[0, 1]),
c: CGFloat(self[1, 0]),
d: CGFloat(self[1, 1]),
tx: CGFloat(self[0, 3]),
ty: CGFloat(self[1, 3]))
}
/// The CATransform3D version of the receiver.
/// - returns: A `CATransform3D` that is equivalent to the receiver.
public var transform3D: CATransform3D {
let t = CATransform3D(
m11: CGFloat(self[0, 0]),
m12: CGFloat(self[0, 1]),
m13: CGFloat(self[0, 2]),
m14: CGFloat(self[0, 3]),
m21: CGFloat(self[1, 0]),
m22: CGFloat(self[1, 1]),
m23: CGFloat(self[1, 2]),
m24: CGFloat(self[1, 3]),
m31: CGFloat(self[2, 0]),
m32: CGFloat(self[2, 1]),
m33: CGFloat(self[2, 2]),
m34: CGFloat(self[2, 3]),
m41: CGFloat(self[3, 0]),
m42: CGFloat(self[3, 1]),
m43: CGFloat(self[3, 2]),
m44: CGFloat(self[3, 3])
)
return t
}
}
/// Returns true if the two source Transform structs share identical dimensions
/// - parameter lhs: The first transform to compare
/// - parameter rhs: The second transform to compare
/// - returns: A boolean, `true` if the both transforms are equal
public func == (lhs: Transform, rhs: Transform) -> Bool {
var equal = true
for col in 0...3 {
for row in 0...3 {
equal = equal && lhs[row, col] == rhs[row, col]
}
}
return equal
}
/// Transform matrix multiplication
/// - parameter lhs: The first transform to multiply
/// - parameter rhs: The second transform to multiply
/// - returns: A new transform that is the result of multiplying `lhs` and `rhs`
public func * (lhs: Transform, rhs: Transform) -> Transform {
var t = Transform()
for col in 0...3 {
for row in 0...3 {
t[row, col] = lhs[row, 0] * rhs[0, col] + lhs[row, 1] * rhs[1, col] + lhs[row, 2] * rhs[2, col] + lhs[row, 3] * rhs[3, col]
}
}
return t
}
/// Transform matrix scalar multiplication
/// - parameter t: The transform to scale
/// - parameter s: A scalar value to apply to the transform
/// - returns: A new trasform whose values are the scalar multiple of `t`
public func * (t: Transform, s: Double) -> Transform {
var r = Transform()
for col in 0...3 {
for row in 0...3 {
r[row, col] = t[row, col] * s
}
}
return r
}
/// Transform matrix scalar multiplication
/// - parameter s: A scalar value to apply to the transform
/// - parameter t: The transform to scale
/// - returns: A new trasform whose values are the scalar multiple of `t`
public func * (s: Double, t: Transform) -> Transform {
return t * s
}
/// Concatenate two transformations. This is the same as t2 * t1.
/// - parameter t1: The first transform to contatenate
/// - parameter t2: The second transform to contatenate
/// - returns: A new transform that is the contcatenation of `t1` and `t2`
public func concat(_ t1: Transform, t2: Transform) -> Transform {
return t2 * t1
}
/// Calculates the inverse of a transfomation.
/// - parameter t: The transform to invert
/// - returns: A new transform that is the inverse of `t`
public func inverse(_ t: Transform) -> Transform? {
var N: __CLPK_integer = 4
var error: __CLPK_integer = 0
var pivot = [__CLPK_integer](repeating: 0, count: 4)
var matrix: [__CLPK_doublereal] = t.matrix
// LU factorisation
dgetrf_(&N, &N, &matrix, &N, &pivot, &error)
if error != 0 {
return nil
}
// matrix inversion
var workspace = [__CLPK_doublereal](repeating: 0, count: 4)
dgetri_(&N, &matrix, &N, &pivot, &workspace, &N, &error)
if error != 0 {
return nil
}
var r = Transform()
r.matrix = matrix
return r
}
|
mit
|
d08e492e5e60f2e902f0efb954623c05
| 34.996885 | 135 | 0.570749 | 3.515364 | false | false | false | false |
jeremy-w/adian
|
Adian/ComposePostViewController.swift
|
1
|
1541
|
/*
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 Cocoa
class ComposePostViewController: NSViewController {
static let storyboardID = "Adian.ComposePostViewController"
static var storyboard: NSStoryboard? {
let mainStoryboard = NSStoryboard(name: "Main", bundle: NSBundle.mainBundle())
return mainStoryboard
}
static func instantiate() -> ComposePostViewController {
let instance = storyboard!.instantiateControllerWithIdentifier(storyboardID)
return instance as! ComposePostViewController
}
/// Provides required components not embedded in the storyboard.
///
/// Commonly called from `prepareForSegue(_:sender:)`.
func configure(poster: Poster) {
self.poster = poster
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
// MARK: Enter Post
@IBOutlet var messageField: NSTextView!
// MARK: Send Post
@IBOutlet var sendButton: NSButton!
var poster: Poster?
@IBAction func sendButtonAction(sender: NSButton?) {
sendMessage()
}
func sendMessage() {
let message = messageField.string ?? ""
poster?.postMessage(message)
}
}
|
mpl-2.0
|
5ab4697e1b74280a92d6a8211fc6fd85
| 23.460317 | 86 | 0.663855 | 4.954984 | false | false | false | false |
regini/inSquare
|
inSquareAppIOS/inSquareAppIOS/SwiftRegex.swift
|
1
|
5770
|
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by John Holdsworth on 26/06/2014.
// Copyright (c) 2014 John Holdsworth.
//
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
//
// This code is in the public domain from:
// https://github.com/johnno1962/SwiftRegex
//
import Foundation
infix operator <~ { associativity none precedence 130 }
private var swiftRegexCache = [String: NSRegularExpression]()
internal final class SwiftRegex: NSObject, BooleanType {
var target:String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
do {
let regex = try NSRegularExpression(pattern: pattern, options:
NSRegularExpressionOptions.DotMatchesLineSeparators)
swiftRegexCache[pattern] = regex
self.regex = regex
} catch let error as NSError {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
super.init()
}
private static func failure(message: String) {
fatalError("SwiftRegex: \(message)")
}
private var targetRange: NSRange {
return NSRange(location: 0,length: target.utf16.count)
}
private func substring(range: NSRange) -> String? {
if range.location != NSNotFound {
return (target as NSString).substringWithRange(range)
} else {
return nil
}
}
func doesMatch(options: NSMatchingOptions!) -> Bool {
return range(options).location != NSNotFound
}
func range(options: NSMatchingOptions) -> NSRange {
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
}
func match(options: NSMatchingOptions) -> String? {
return substring(range(options))
}
func groups() -> [String]? {
return groupsForMatch(regex.firstMatchInString(target as String, options:
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
}
private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? {
guard let match = match else {
return nil
}
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
}
}
return groups
}
subscript(groupno: Int) -> String? {
get {
return groups()?[groupno]
}
set(newValue) {
if newValue == nil {
return
}
for match in Array(matchResults().reverse()) {
let replacement = regex.replacementStringForResult(match,
inString: target as String, offset: 0, template: newValue!)
let mut = NSMutableString(string: target)
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
target = mut as String
}
}
}
func matchResults() -> [NSTextCheckingResult] {
let matches = regex.matchesInString(target as String, options:
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
as [NSTextCheckingResult]
return matches
}
func ranges() -> [NSRange] {
return matchResults().map { $0.range }
}
func matches() -> [String] {
return matchResults().map( { self.substring($0.range)!})
}
func allGroups() -> [[String]?] {
return matchResults().map { self.groupsForMatch($0) }
}
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults() {
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
}
return out
}
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
options:NSMatchingOptions) -> String {
let out = NSMutableString()
var pos = 0
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
let matchRange = match!.range
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
out.appendString( substitution(match!, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
return out as String
}
var boolValue: Bool {
return doesMatch(nil)
}
}
extension String {
subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
}
}
extension String {
subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: nil)
}
}
func <~ (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: [])
}
|
mit
|
53d37ce83cd3bedebe8f8480adcf9da3
| 31.41573 | 122 | 0.590988 | 4.931624 | false | false | false | false |
rlisle/ParticleIoT
|
iOS/Patriot/Patriot/Models/ActivityModel.swift
|
1
|
525
|
//
// ActivityModel.swift
// rvcp
//
// Created by Ron Lisle on 10/7/16.
// Copyright © 2016 Ron Lisle. All rights reserved.
//
import UIKit
class Activity
{
let name: String
var onImage: UIImage
var offImage: UIImage
var isActive: Bool
init(name: String, isActive: Bool = false) {
self.name = name
self.isActive = isActive
self.onImage = #imageLiteral(resourceName: "LightOn")
self.offImage = #imageLiteral(resourceName: "LightOff")
}
}
|
mit
|
96eeb02cf36beca4590726d3a9005492
| 19.96 | 63 | 0.610687 | 3.638889 | false | false | false | false |
Nana-Muthuswamy/TwitterLite
|
TwitterLite/Date+Extension.swift
|
1
|
846
|
//
// Date+Extension.swift
// TwitterLite
//
// Created by Nana on 4/16/17.
// Copyright © 2017 Nana. All rights reserved.
//
import Foundation
extension Date {
var readableValue: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d, h:mm a"
return formatter.string(from: self)
}
var relativeValue: String {
let timeInterval = Int(abs(self.timeIntervalSinceNow))
if timeInterval < 60 {
return "\(timeInterval)s"
} else if timeInterval < 3600 {
return "\(timeInterval/60)m"
} else if timeInterval < 86400 {
return "\(Int(timeInterval/1440))h"
} else {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d"
return formatter.string(from: self)
}
}
}
|
mit
|
b9bc22ee884915e1ce0a63d33d335da2
| 22.472222 | 62 | 0.579882 | 4.28934 | false | false | false | false |
optimizely/objective-c-sdk
|
Pods/Mixpanel-swift/Mixpanel/TweakStore.swift
|
2
|
7444
|
//
// TweakStore.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/5/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import UIKit
/// Looks up the persisted state for tweaks.
public final class TweakStore {
/// The "tree structure" for our Tweaks UI.
var tweakCollections: [String: TweakCollection] = [:]
/// Useful when exporting or checking that a tweak exists in tweakCollections
var allTweaks: Set<AnyTweak>
/// We hold a reference to the storeName so we can have a better error message if a tweak doesn't exist in allTweaks.
private let storeName: String
/// Caches "single" bindings - when a tweak is updated, we'll call each of the corresponding bindings.
private var tweakBindings: [String: [AnyTweakBinding]] = [:]
/// Caches "multi" bindings - when any tweak in a Set is updated, we'll call each of the corresponding bindings.
private var tweakSetBindings: [Set<AnyTweak>: [() -> Void]] = [:]
/// Persists tweaks' currentValues and maintains them on disk.
private let persistence: TweakPersistency
/// Determines whether tweaks are enabled, and whether the tweaks UI is accessible
internal let enabled: Bool
///
///
/**
Creates a TweakStore, with information persisted on-disk.
If you want to have multiple TweakStores in your app, you can pass in a unique storeName to keep it separate from others on disk.
- parameter storeName: the name of the store (optional)
- parameter enabled: if debugging is enabled or not
*/
init(storeName: String = "Tweaks", enabled: Bool) {
self.persistence = TweakPersistency(identifier: storeName)
self.storeName = storeName
self.enabled = enabled
self.allTweaks = Set()
}
/// A method for adding Tweaks to the environment
func addTweaks(_ tweaks: [TweakClusterType]) {
self.allTweaks.formUnion(Set(tweaks.reduce(into: []) { $0.append(contentsOf: $1.tweakCluster) }))
self.allTweaks.forEach { tweak in
// Find or create its TweakCollection
var tweakCollection: TweakCollection
if let existingCollection = tweakCollections[tweak.collectionName] {
tweakCollection = existingCollection
} else {
tweakCollection = TweakCollection(title: tweak.collectionName)
tweakCollections[tweakCollection.title] = tweakCollection
}
// Find or create its TweakGroup
var tweakGroup: TweakGroup
if let existingGroup = tweakCollection.tweakGroups[tweak.groupName] {
tweakGroup = existingGroup
} else {
tweakGroup = TweakGroup(title: tweak.groupName)
}
// Add the tweak to the tree
tweakGroup.tweaks[tweak.tweakName] = tweak
tweakCollection.tweakGroups[tweakGroup.title] = tweakGroup
tweakCollections[tweakCollection.title] = tweakCollection
}
}
/// Returns the current value for a given tweak
func assign<T>(_ tweak: Tweak<T>) -> T {
return self.currentValueForTweak(tweak)
}
/**
The bind function for Tweaks. This is meant for binding Tweaks to the relevant components.
- parameter tweak: the tweak to bind
- parameter binding: the binding to issue for the tweak
*/
func bind<T>(_ tweak: Tweak<T>, binding: @escaping (T) -> Void) {
// Create the TweakBinding<T>, and wrap it in our type-erasing AnyTweakBinding
let tweakBinding = TweakBinding(tweak: tweak, binding: binding)
let anyTweakBinding = AnyTweakBinding(tweakBinding: tweakBinding)
// Cache the binding
let existingTweakBindings = tweakBindings[tweak.persistenceIdentifier] ?? []
tweakBindings[tweak.persistenceIdentifier] = existingTweakBindings + [anyTweakBinding]
// Then immediately apply the binding on whatever current value we have
binding(currentValueForTweak(tweak))
}
func bindMultiple(_ tweaks: [TweakType], binding: @escaping () -> Void) {
// Convert the array (which makes it easier to call a `bindTweakSet`) into a set (which makes it possible to cache the tweakSet)
let tweakSet = Set(tweaks.map(AnyTweak.init))
// Cache the cluster binding
let existingTweakSetBindings = tweakSetBindings[tweakSet] ?? []
tweakSetBindings[tweakSet] = existingTweakSetBindings + [binding]
// Immediately call the binding
binding()
}
// MARK: - Internal
/// Resets all tweaks to their `defaultValue`
internal func reset() {
persistence.clearAllData()
// Go through all tweaks in our library, and call any bindings they're attached to.
tweakCollections.values.reduce(into: []) {
$0.append(contentsOf: $1.sortedTweakGroups.reduce(into: []) {
$0.append(contentsOf: $1.sortedTweaks)
})
}
.forEach { updateBindingsForTweak($0) }
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T {
if allTweaks.contains(AnyTweak(tweak: tweak)) {
return enabled ? persistence.currentValueForTweak(tweak) ?? tweak.defaultValue : tweak.defaultValue
} else {
Logger.error(message: "Error: the tweak \"\(tweak.tweakIdentifier)\" isn't included in the tweak store \"\(storeName)\"." +
"Returning the default value.")
return tweak.defaultValue
}
}
internal func currentViewDataForTweak(_ tweak: AnyTweak) -> TweakViewData {
let cachedValue = persistence.persistedValueForTweakIdentifiable(tweak)
switch tweak.tweakDefaultData {
case let .boolean(defaultValue: defaultValue):
let currentValue = cachedValue as? Bool ?? defaultValue
return .boolean(value: currentValue, defaultValue: defaultValue)
case let .integer(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? Int ?? defaultValue
return .integer(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .float(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? CGFloat ?? defaultValue
return .float(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .doubleTweak(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? Double ?? defaultValue
return .doubleTweak(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .string(defaultValue: defaultValue):
let currentValue = cachedValue as? String ?? defaultValue
return .string(value: currentValue, defaultValue: defaultValue)
}
}
internal func setValue(_ viewData: TweakViewData, forTweak tweak: AnyTweak) {
persistence.setValue(viewData.value, forTweakIdentifiable: tweak)
updateBindingsForTweak(tweak)
}
// MARK - Private
/// Update Bindings for the Tweaks when a change is needed.
private func updateBindingsForTweak(_ tweak: AnyTweak) {
// Find any 1-to-1 bindings and update them
tweakBindings[tweak.persistenceIdentifier]?.forEach {
$0.applyBindingWithValue(currentViewDataForTweak(tweak).value)
}
// Find any cluster bindings and update them
for (tweakSet, bindingsArray) in tweakSetBindings {
if tweakSet.contains(tweak) {
bindingsArray.forEach { $0() }
}
}
}
}
extension TweakStore {
internal var sortedTweakCollections: [TweakCollection] {
return tweakCollections
.sorted { $0.0 < $1.0 }
.map { return $0.1 }
}
}
|
apache-2.0
|
a173b7d00d9e80831a10fff68dbb3006
| 37.968586 | 135 | 0.700793 | 4.137298 | false | false | false | false |
netguru/inbbbox-ios
|
Inbbbox/Source Files/Model/Protocols/ProjectType.swift
|
1
|
1238
|
//
// ProjectType.swift
// Inbbbox
//
// Created by Lukasz Wolanczyk on 2/18/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
/// Interface for Project and ManagedProject.
protocol ProjectType {
/// Unique identifier.
var identifier: String { get }
/// Name of the Project.
var name: String? { get }
/// Description of the Project.
var attributedDescription: NSAttributedString? { get }
/// Date when Project was created.
var createdAt: Date { get }
/// Number of shots associated to this Project.
var shotsCount: UInt { get }
}
func == (lhs: ProjectType, rhs: ProjectType) -> Bool {
return lhs.identifier == rhs.identifier
}
func == (lhs: [ProjectType], rhs: [ProjectType]) -> Bool {
guard lhs.count == rhs.count else { return false }
var indexingGenerators = (left: lhs.makeIterator(), right: rhs.makeIterator())
var isEqual = true
while let leftElement = indexingGenerators.left.next(),
let rightElement = indexingGenerators.right.next(), isEqual {
isEqual = leftElement == rightElement
}
return isEqual
}
func != (lhs: [ProjectType], rhs: [ProjectType]) -> Bool {
return !(lhs == rhs)
}
|
gpl-3.0
|
a949fb4d468e20c56b5f280ad3c02eb2
| 23.254902 | 82 | 0.64996 | 3.952077 | false | false | false | false |
RevenueCat/purchases-ios
|
Sources/Purchasing/StoreKitAbstractions/SK2StoreProduct.swift
|
1
|
4289
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// SK2StoreProduct.swift
//
// Created by Nacho Soto on 12/20/21.
import StoreKit
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
internal struct SK2StoreProduct: StoreProductType {
init(sk2Product: SK2Product) {
#if swift(<5.7)
self._underlyingSK2Product = sk2Product
#else
self.underlyingSK2Product = sk2Product
#endif
}
#if swift(<5.7)
// We can't directly store instances of StoreKit.Product, since that causes
// linking issues in iOS < 15, even with @available checks correctly in place.
// So instead, we store the underlying product as Any and wrap it with casting.
// https://openradar.appspot.com/radar?id=4970535809187840
private let _underlyingSK2Product: Any
var underlyingSK2Product: SK2Product {
// swiftlint:disable:next force_cast
_underlyingSK2Product as! SK2Product
}
#else
let underlyingSK2Product: SK2Product
#endif
private let priceFormatterProvider: PriceFormatterProvider = .init()
var productCategory: StoreProduct.ProductCategory {
return self.productType.productCategory
}
var productType: StoreProduct.ProductType {
return .init(self.underlyingSK2Product.type)
}
var localizedDescription: String { underlyingSK2Product.description }
var currencyCode: String? {
// note: if we ever need more information from the jsonRepresentation object, we
// should use Codable or another decoding method to clean up this code.
let attributes = jsonDict["attributes"] as? [String: Any]
let offers = attributes?["offers"] as? [[String: Any]]
return offers?.first?["currencyCode"] as? String
}
var price: Decimal { underlyingSK2Product.price }
var localizedPriceString: String { underlyingSK2Product.displayPrice }
var productIdentifier: String { underlyingSK2Product.id }
var isFamilyShareable: Bool { underlyingSK2Product.isFamilyShareable }
var localizedTitle: String { underlyingSK2Product.displayName }
var priceFormatter: NumberFormatter? {
guard let currencyCode = self.currencyCode else {
Logger.appleError("Can't initialize priceFormatter for SK2 product! Could not find the currency code")
return nil
}
return priceFormatterProvider.priceFormatterForSK2(withCurrencyCode: currencyCode)
}
var subscriptionGroupIdentifier: String? {
underlyingSK2Product.subscription?.subscriptionGroupID
}
private var jsonDict: [String: Any] {
let decoded = try? JSONSerialization.jsonObject(with: self.underlyingSK2Product.jsonRepresentation, options: [])
return decoded as? [String: Any] ?? [:]
}
var subscriptionPeriod: SubscriptionPeriod? {
guard let skSubscriptionPeriod = underlyingSK2Product.subscription?.subscriptionPeriod else {
return nil
}
return SubscriptionPeriod.from(sk2SubscriptionPeriod: skSubscriptionPeriod)
}
var introductoryDiscount: StoreProductDiscount? {
self.underlyingSK2Product.subscription?.introductoryOffer
.flatMap { StoreProductDiscount(sk2Discount: $0, currencyCode: self.currencyCode) }
}
var discounts: [StoreProductDiscount] {
(self.underlyingSK2Product.subscription?.promotionalOffers ?? [])
.compactMap { StoreProductDiscount(sk2Discount: $0, currencyCode: self.currencyCode) }
}
}
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
extension SK2StoreProduct: Hashable {
static func == (lhs: SK2StoreProduct, rhs: SK2StoreProduct) -> Bool {
return lhs.underlyingSK2Product == rhs.underlyingSK2Product
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.underlyingSK2Product)
}
}
#if swift(<5.7)
// `SK2Product` isn't `Sendable` until iOS 16.0 / Swift 5.7
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
extension SK2StoreProduct: @unchecked Sendable {}
#endif
|
mit
|
7dd74fd8390fa07056e6053ab5a52c48
| 33.58871 | 120 | 0.69993 | 4.297595 | false | false | false | false |
milseman/swift
|
test/IDE/print_ast_overlay.swift
|
8
|
2119
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-module -module-name Foo -o %t -F %S/Inputs/mock-sdk %s
//
// RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo -accessibility-filter-public > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_WITH_OVERLAY -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_NO_INTERNAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo.FooSub > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_WITHOUT_OVERLAY -strict-whitespace < %t.printed.txt
// XFAIL: linux
// RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo -accessibility-filter-public -annotate-print > %t.annotated.txt
// RUN: %FileCheck %s -check-prefix=PASS_ANNOTATED -strict-whitespace < %t.annotated.txt
// REQUIRES: executable_test
@_exported import Foo
public func overlay_func() {}
internal func overlay_func_internal() {}
public class FooOverlayClassBase {
public func f() {}
}
public class FooOverlayClassDerived : FooOverlayClassBase {
override public func f() {}
}
// Check that given a top-level module with an overlay, AST printer prints
// declarations from both of them.
// PASS_WITH_OVERLAY-LABEL: {{^}}class FooClassBase {
// PASS_WITH_OVERLAY-LABEL: {{^}}class FooOverlayClassDerived : FooOverlayClassBase {
// PASS_WITH_OVERLAY-NEXT: {{^}} override func f()
// PASS_WITH_OVERLAY: {{^}}func overlay_func(){{$}}
// But when printing a submodule, AST printer should not print the overlay,
// because overlay declarations are logically in the top-level module.
// PASS_WITHOUT_OVERLAY-NOT: overlay_func
// PASS_NO_INTERNAL-NOT: overlay_func_internal
// PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>Foo</ref>.<ref:module>FooSub</ref></decl>
// PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>Foo</ref></decl>
// PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>FooHelper</ref></decl>
|
apache-2.0
|
3c3bcb6ec6e1d58cdaa13558bd83e22d
| 45.065217 | 177 | 0.720151 | 3.280186 | false | true | false | false |
EZ-NET/LGTM
|
LGTM/ViewController.swift
|
1
|
3729
|
//
// ViewController.swift
// LGTM
//
// Created by toshi0383 on 2015/08/26.
// Copyright © 2015年 toshi0383. All rights reserved.
//
import AppKit
import Async
enum ViewControllerType:String {
case Lgtmin = "lgtmin"
case Favorites = "favorites"
}
class ViewController: NSViewController {
@IBOutlet weak var copyButton: NSButton!
@IBOutlet weak var loveButton: NSButton!
@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var imageView: NSImageView!
private var monitor: AnyObject!
private var lgtm:Lgtm? {
didSet {
syncUI()
}
}
internal var type:ViewControllerType!
override func viewDidLoad() {
super.viewDidLoad()
/// textField
textField.preferredMaxLayoutWidth = 270
/// imageView
imageView.animates = true
imageView.imageScaling = NSImageScaling.ScaleProportionallyUpOrDown
imageView.canDrawSubviewsIntoLayer = true
/// syncUI
syncUI()
/// button actions
type = ViewControllerType(rawValue: self.title!)
copyButton.action = "copyAction"
copyButton.target = self
switch type! {
case .Lgtmin:
loveButton.action = "favoriteAction"
loveButton.target = self
case .Favorites:
break
}
}
override func viewWillAppear() {
super.viewWillAppear()
view.layer?.backgroundColor = NSColor.whiteColor().CGColor
}
override func viewWillDisappear() {
super.viewWillDisappear()
NSEvent.removeMonitor(monitor)
}
override func viewDidAppear() {
super.viewDidAppear()
configureEventMonitor()
}
}
extension ViewController {
private func syncUI() {
if let lgtm = lgtm {
textField.stringValue = lgtm.markdown("LGTM")
textField.selectText(nil)
imageView.image = lgtm.image
switch type! {
case .Lgtmin:
break
case .Favorites:
// loveButton.hidden = true
break
}
}
}
private func configureEventMonitor() {
monitor = NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask) {[unowned self] e in
let str:String = e.characters ?? ""
switch (str, e.keyCode) {
case ("c", _):
if e.modifierFlags.contains(NSEventModifierFlags.CommandKeyMask) {
self.copyButton.performClick(self.copyButton)
}
case (" ", 49):
if let newlgtm = self.getLgtm() where newlgtm != self.lgtm {
self.lgtm = newlgtm
}
case ("s", _):
if e.modifierFlags.contains(NSEventModifierFlags.CommandKeyMask) {
if self.type == .Lgtmin {
self.loveButton.performClick(self.loveButton)
}
}
default:
break
}
return e
}
}
internal func copyAction() {
let gp = NSPasteboard.generalPasteboard()
gp.declareTypes([NSStringPboardType], owner: nil)
_ = gp.clearContents()
self.textField.selectText(nil)
if gp.writeObjects([self.textField.stringValue]) { }
}
internal func favoriteAction() {
copyAction()
if let lgtm = lgtm {
Provider.favLgtm(lgtm)
}
}
private func getLgtm() -> Lgtm? {
switch type! {
case .Lgtmin:
return Provider.popRandomLgtm()
case .Favorites:
return Provider.popFavoriteLgtm()
}
}
}
|
mit
|
9b6b0426bcfc2fea9375a73b51920275
| 29.048387 | 108 | 0.563875 | 4.622829 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PinchToZoom.swift
|
1
|
4660
|
//
// PinchToZoom.swift
// Telegram
//
// Created by Mikhail Filimonov on 15.04.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
protocol PinchableView : NSView {
func update(size: NSSize)
}
final class PinchToZoom {
private weak var parentView: NSView?
private var view: PinchableView?
private var magnify: NSMagnificationGestureRecognizer!
private var initialSize: NSSize = .zero
private var initialOrigin: NSPoint {
guard let parent = parentView, let window = parent.window else {
return .zero
}
var point = window.contentView!.convert(NSZeroPoint, from: parent)
point = point.offset(dx: 0, dy: -parent.frame.height)
return point
}
private var currentMagnify: CGFloat = 0
private var animation: DisplayLinkAnimator?
private let disposable = MetaDisposable()
init(parentView: NSView?) {
self.parentView = parentView
self.magnify = NSMagnificationGestureRecognizer(target: self, action: #selector(zoomIn(_:)))
}
func add(to view: PinchableView, size: NSSize) {
self.initialSize = size
if view.isEqual(to: view) {
self.view?.removeGestureRecognizer(magnify)
self.view = view
view.addGestureRecognizer(magnify)
}
}
func remove() {
self.initialSize = .zero
self.view?.removeGestureRecognizer(magnify)
}
deinit {
view?.removeGestureRecognizer(magnify)
disposable.dispose()
}
@objc func zoomIn(_ gesture: NSMagnificationGestureRecognizer) {
guard let parentView = parentView, let view = self.view, let window = parentView.window as? Window else {
return
}
if view.visibleRect == .zero {
return
}
let maxMagnification: CGFloat = 2
self.currentMagnify = min(max(1, 1 + gesture.magnification), maxMagnification)
disposable.set(nil)
let updateMagnify:(CGFloat)->Void = { [weak self, weak view] magnifyValue in
guard let `self` = self, let view = view else {
return
}
let updatedSize = NSMakeSize(round(self.initialSize.width * magnifyValue), round(self.initialSize.height * magnifyValue))
let lastPoint = window.contentView!.focus(NSMakeSize(self.initialSize.width * maxMagnification, self.initialSize.height * maxMagnification)).origin
let x = lastPoint.x - self.initialOrigin.x
let y = lastPoint.y - self.initialOrigin.y
let coef = min((magnifyValue - 1), 1)
let bestPoint = NSMakePoint(round(self.initialOrigin.x + x * coef), round(self.initialOrigin.y + y * coef))
view.frame = CGRect(origin: bestPoint, size: updatedSize)
self.currentMagnify = magnifyValue
}
self.animation = nil
let returnView:(Bool)->Void = { [weak self, weak view] animated in
guard let strongSelf = self else {
return
}
view?.update(size: strongSelf.initialSize)
strongSelf.animation = DisplayLinkAnimator(duration: 0.2, from: strongSelf.currentMagnify, to: 1, update: { current in
updateMagnify(current)
}, completion: { [weak view] in
if let view = view {
view.setFrameOrigin(.zero)
strongSelf.parentView?.addSubview(view)
}
})
}
switch gesture.state {
case .began:
var point = window.contentView!.convert(NSZeroPoint, from: view)
point = point.offset(dx: 0, dy: -view.frame.height)
view.setFrameOrigin(point)
window.contentView?.addSubview(view)
let updatedSize = NSMakeSize(round(self.initialSize.width * maxMagnification), round(self.initialSize.height * maxMagnification))
view.update(size: updatedSize)
case .possible:
break
case .changed:
let magnifyValue = min(max(1, 1 + gesture.magnification), maxMagnification)
updateMagnify(magnifyValue)
case .ended:
returnView(true)
case .cancelled:
returnView(true)
case .failed:
returnView(true)
@unknown default:
break
}
}
}
|
gpl-2.0
|
e8fa5367449eb0b6c87023519c75a5b1
| 31.809859 | 159 | 0.581455 | 4.827979 | false | false | false | false |
SwiftGFX/SwiftMath
|
Sources/easing.swift
|
1
|
7545
|
//
// easing.swift
// org.SwiftGFX.SwiftMath
//
// Created by Andrey Volodin on 03.09.16.
//
//
#if (os(OSX) || os(iOS) || os(tvOS) || os(watchOS))
import Darwin
#elseif os(Linux) || os(Android)
import Glibc
#endif
// MARK: Linear
public func linear(_ time: Float) -> Float {
return time
}
// MARK: Sine Ease
public func sineEaseIn(_ time: Float) -> Float {
return -cos(time * Angle.pi_2) + 1
}
public func sineEaseOut(_ time: Float) -> Float {
return sin(time * Angle.pi_2)
}
public func sineEaseInOut(_ time: Float) -> Float {
return -0.5 * (cos(Angle.pi * time) - 1)
}
// MARK: Quad Ease
public func quadEaseIn(_ time: Float) -> Float {
return time * time
}
public func quadEaseOut(_ time: Float) -> Float {
return -time * (time - 2)
}
public func quadEaseInOut(_ time: Float) -> Float {
var time = time * 2
if time < 1 {
return 0.5 * time * time
}
time -= 1
return -0.5 * (time * (time - 2) - 1)
}
// MARK: Cubic Ease
public func cubicEaseIn(_ time: Float) -> Float {
return time * time * time
}
public func cubicEaseOut(_ time: Float) -> Float {
var time = time
time -= 1
return (time * time * time + 1)
}
public func cubicEaseInOut(_ time: Float) -> Float {
var time = time * 2
if time < 1 {
return 0.5 * time * time * time
}
time -= 2
return 0.5 * (time * time * time + 2)
}
// MARK: Quart Ease
public func quartEaseIn(_ time: Float) -> Float {
return time * time * time * time
}
public func quartEaseOut(_ time: Float) -> Float {
var time = time
time -= 1
return -(time * time * time * time - 1)
}
public func quartEaseInOut(_ time: Float) -> Float {
var time = time
time = time * 2
if time < 1 {
return 0.5 * time * time * time * time
}
time -= 2
return -0.5 * (time * time * time * time - 2)
}
// MARK: Quint Ease
public func quintEaseIn(_ time: Float) -> Float {
return time * time * time * time * time
}
public func quintEaseOut(_ time: Float) -> Float {
var time = time
time -= 1
return (time * time * time * time * time + 1)
}
public func quintEaseInOut(_ time: Float) -> Float {
var time = time * 2
if time < 1 {
return 0.5 * time * time * time * time * time
}
time -= 2
return 0.5 * (time * time * time * time * time + 2)
}
// MARK: Expo Ease
public func expoEaseIn(_ time: Float) -> Float {
return time == 0 ? 0 : powf(2, 10 * (time / 1 - 1)) - 1 * 0.001
}
public func expoEaseOut(_ time: Float) -> Float {
return time == 1 ? 1 : (-powf(2, -10 * time / 1) + 1)
}
public func expoEaseInOut(_ time: Float) -> Float {
var time = time
time /= 0.5
if time < 1 {
time = 0.5 * powf(2, 10 * (time - 1))
}
else {
time = 0.5 * (-powf(2, -10 * (time - 1)) + 2)
}
return time
}
// MARK: Circ Ease
public func circEaseIn(_ time: Float) -> Float {
return -(sqrt(1 - time * time) - 1)
}
public func circEaseOut(_ time: Float) -> Float {
var time = time
time = time - 1
return sqrt(1 - time * time)
}
public func circEaseInOut(_ time: Float) -> Float {
var time = time
time = time * 2
if time < 1 {
return -0.5 * (sqrt(1 - time * time) - 1)
}
time -= 2
return 0.5 * (sqrt(1 - time * time) + 1)
}
// MARK: Elastic Ease
public func elasticEaseIn(_ time: Float, period: Float) -> Float {
var time = time
var newT: Float = 0
if time == 0 || time == 1 {
newT = time
}
else {
let s: Float = period / 4
time = time - 1
newT = -powf(2, 10 * time) * sin((time - s) * Angle.pi2 / period)
}
return newT
}
public func elasticEaseOut(_ time: Float, period: Float) -> Float {
var newT: Float = 0
if time == 0 || time == 1 {
newT = time
}
else {
let s: Float = period / 4
newT = powf(2, -10 * time) * sin((time - s) * Angle.pi2 / period) + 1
}
return newT
}
public func elasticEaseInOut(_ time: Float, period: Float) -> Float {
var time = time
var period = period
var newT: Float = 0
if time == 0 || time == 1 {
newT = time
}
else {
time = time * 2
if period == 0.0 {
period = 0.3 * 1.5
}
let s: Float = period / 4
time = time - 1
if time < 0 {
newT = -0.5 * powf(2, 10 * time) * sin((time - s) * Angle.pi2 / period)
}
else {
newT = powf(2, -10 * time) * sin((time - s) * Angle.pi2 / period) * 0.5 + 1
}
}
return newT
}
// MARK: Back Ease
public func backEaseIn(_ time: Float, overshoot: Float) -> Float {
let overshoot: Float = 1.70158
return time * time * ((overshoot + 1) * time - overshoot)
}
public func backEaseOut(_ time: Float, overshoot: Float) -> Float {
let overshoot: Float = 1.70158
var time = time
time = time - 1
return time * time * ((overshoot + 1) * time + overshoot) + 1
}
public func backEaseInOut(_ time: Float, overshoot: Float) -> Float {
let overshoot: Float = 1.70158 * 1.525
var time = time
time = time * 2
if time < 1 {
return (time * time * ((overshoot + 1) * time - overshoot)) / 2
}
else {
time = time - 2
time *= time
time *= (overshoot + 1) * time + overshoot
return time / 2 + 1
}
}
// MARK: Bounce Ease
public func bounceTime(_ time: Float) -> Float {
var time = time
if time < 1 / 2.75 {
return 7.5625 * time * time
}
else if time < 2 / 2.75 {
time -= 1.5 / 2.75
return 7.5625 * time * time + 0.75
}
else if time < 2.5 / 2.75 {
time -= 2.25 / 2.75
return 7.5625 * time * time + 0.9375
}
time -= 2.625 / 2.75
return 7.5625 * time * time + 0.984375
}
public func bounceEaseIn(_ time: Float) -> Float {
return 1 - bounceTime(1 - time)
}
public func bounceEaseOut(_ time: Float) -> Float {
return bounceTime(time)
}
public func bounceEaseInOut(_ time: Float) -> Float {
var time = time
var newT: Float = 0
if time < 0.5 {
time = time * 2
newT = (1 - bounceTime(1 - time)) * 0.5
}
else {
newT = bounceTime(time * 2 - 1) * 0.5 + 0.5
}
return newT
}
// MARK: Custom Ease
public func customEase(_ time: Float, easingParam: [Float]) -> Float {
guard easingParam.count == 8 else {
print("WARNING: Wrong easing param")
return time
}
let tt: Float = 1 - time
return easingParam[1] * tt * tt * tt + 3 * easingParam[3] * time * tt * tt + 3 * easingParam[5] * time * time * tt + easingParam[7] * time * time * time
}
public func easeIn(_ time: Float, rate: Float) -> Float {
return powf(time, rate)
}
public func easeOut(_ time: Float, rate: Float) -> Float {
return powf(time, 1 / rate)
}
public func easeInOut(_ time: Float, rate: Float) -> Float {
var time = time
time *= 2
if time < 1 {
return 0.5 * powf(time, rate)
}
else {
return (1.0 - 0.5 * powf(2 - time, rate))
}
}
public func quadraticIn(_ time: Float) -> Float {
return powf(time, 2)
}
public func quadraticOut(_ time: Float) -> Float {
return -time * (time - 2)
}
public func quadraticInOut(_ time: Float) -> Float {
var time = time
var resultTime: Float = time
time = time * 2
if time < 1 {
resultTime = time * time * 0.5
}
else {
time -= 1
resultTime = -0.5 * (time * (time - 2) - 1)
}
return resultTime
}
|
bsd-2-clause
|
6ec1664a6d83b5a64d90d8ecfd0f0337
| 22.215385 | 156 | 0.543406 | 3.238197 | false | false | false | false |
wess/reddift
|
reddift.playground/Contents.swift
|
1
|
3908
|
//: Playground - noun: a place where people can play
import Foundation
import reddift
import XCPlayground
func getCAPTCHA(session:Session) {
session.getCAPTCHA({ (result:Result<CAPTCHA>) -> Void in
switch result {
case let .Failure:
println(result.error!.description)
case let .Success:
if let captcha:CAPTCHA = result.value {
let img:UIImage = captcha.image
}
}
})
}
func getReleated(session:Session) {
session.getDuplicatedArticles(Paginator(), thing: Link(id: "37lhsm")) { (result) -> Void in
switch result {
case let .Failure:
println(result.error!.description)
case let .Success:
println(result.value!)
if let array = result.value as? [RedditAny] {
println(array[0])
println(array[1])
if let listing = array[0] as? Listing {
for obj in listing.children {
if let link = obj as? Link {
println(link.title)
}
}
}
if let listing = array[1] as? Listing {
println(listing.children.count)
for obj in listing.children {
if let link = obj as? Link {
println(link.title)
}
}
}
}
}
}
}
func getProfile(session:Session) {
session.getUserProfile("sonson_twit", completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error!.description)
case let .Success:
if let account = result.value as? Account {
println(account.name)
}
}
})
}
func getLinksBy(session:Session) {
let links:[Link] = [Link(id: "37ow7j"), Link(id: "37nvgu")]
session.getLinksById(links, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error!.description)
case let .Success:
if let listing = result.value as? Listing {
println(listing.children.count)
for obj in listing.children {
if let link = obj as? Link {
println(link.title)
}
}
}
}
})
}
func getList(session:Session) {
var subreddit = Subreddit(id: "a")
// subreddit.displayName = "sandboxtest"
session.getRandom(subreddit, completion: { (result) in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
}
})
}
let url: NSURL = NSBundle.mainBundle().URLForResource("test_config.json", withExtension:nil)!
let data = NSData(contentsOfURL: url)!
let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.allZeros, error: nil)
if let json = json as? [String:String] {
if let username = json["username"],
let password = json["password"],
let clientID = json["client_id"],
let secret = json["secret"] {
OAuth2AppOnlyToken.getOAuth2AppOnlyToken(username: username, password: password, clientID: clientID, secret: secret, completion:( { (result:Result<Token>) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
if let token:Token = result.value {
let session = Session(token: token)
getList(session)
}
}
}))
}
}
XCPSetExecutionShouldContinueIndefinitely()
|
mit
|
035dd3e4fe15e892fddfe9edaeeb3ca8
| 31.566667 | 177 | 0.522774 | 4.657926 | false | false | false | false |
Great-Li-Xin/Xcode
|
hangge_756/hangge_756/ysocket/ytcpsocket.swift
|
3
|
6616
|
/*
Copyright (c) <2014>, skysent
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by skysent.
4. Neither the name of the skysent 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 skysent ''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 skysent BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
@_silgen_name("ytcpsocket_connect") func c_ytcpsocket_connect(_ host:UnsafePointer<Int8>,port:Int32,timeout:Int32) -> Int32
@_silgen_name("ytcpsocket_close") func c_ytcpsocket_close(_ fd:Int32) -> Int32
@_silgen_name("ytcpsocket_send") func c_ytcpsocket_send(_ fd:Int32,buff:UnsafePointer<UInt8>,len:Int32) -> Int32
@_silgen_name("ytcpsocket_pull") func c_ytcpsocket_pull(_ fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,timeout:Int32) -> Int32
@_silgen_name("ytcpsocket_listen") func c_ytcpsocket_listen(_ addr:UnsafePointer<Int8>,port:Int32)->Int32
@_silgen_name("ytcpsocket_accept") func c_ytcpsocket_accept(_ onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32
open class TCPClient:YSocket{
/*
* connect to server
* return success or fail with message
*/
open func connect(timeout t:Int)->(Bool,String){
let rs:Int32=c_ytcpsocket_connect(self.addr, port: Int32(self.port), timeout: Int32(t))
if rs>0{
self.fd=rs
return (true,"connect success")
}else{
switch rs{
case -1:
return (false,"qeury server fail")
case -2:
return (false,"connection closed")
case -3:
return (false,"connect timeout")
default:
return (false,"unknow err.")
}
}
}
/*
* close socket
* return success or fail with message
*/
open func close()->(Bool,String){
if let fd:Int32=self.fd{
c_ytcpsocket_close(fd)
self.fd=nil
return (true,"close success")
}else{
return (false,"socket not open")
}
}
/*
* send data
* return success or fail with message
*/
open func send(data d:[UInt8])->(Bool,String){
if let fd:Int32=self.fd{
let sendsize:Int32=c_ytcpsocket_send(fd, buff: d, len: Int32(d.count))
if Int(sendsize)==d.count{
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
* send string
* return success or fail with message
*/
open func send(str s:String)->(Bool,String){
if let fd:Int32=self.fd{
let sendsize:Int32=c_ytcpsocket_send(fd, buff: s, len: Int32(strlen(s)))
if sendsize==Int32(strlen(s)){
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
*
* send nsdata
*/
open func send(data d:Data)->(Bool,String){
if let fd:Int32=self.fd{
var buff:[UInt8] = [UInt8](repeating: 0x0,count: d.count)
(d as NSData).getBytes(&buff, length: d.count)
let sendsize:Int32=c_ytcpsocket_send(fd, buff: buff, len: Int32(d.count))
if sendsize==Int32(d.count){
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
* read data with expect length
* return success or fail with message
*/
open func read(_ expectlen:Int, timeout:Int = -1)->[UInt8]?{
if let fd:Int32 = self.fd{
var buff:[UInt8] = [UInt8](repeating: 0x0,count: expectlen)
let readLen:Int32=c_ytcpsocket_pull(fd, buff: &buff, len: Int32(expectlen), timeout: Int32(timeout))
if readLen<=0{
return nil
}
let rs=buff[0...Int(readLen-1)]
let data:[UInt8] = Array(rs)
return data
}
return nil
}
}
open class TCPServer:YSocket{
open func listen()->(Bool,String){
let fd:Int32=c_ytcpsocket_listen(self.addr, port: Int32(self.port))
if fd>0{
self.fd=fd
return (true,"listen success")
}else{
return (false,"listen fail")
}
}
open func accept()->TCPClient?{
if let serferfd=self.fd{
var buff:[Int8] = [Int8](repeating: 0x0,count: 16)
var port:Int32=0
let clientfd:Int32=c_ytcpsocket_accept(serferfd, ip: &buff,port: &port)
if clientfd<0{
return nil
}
let tcpClient:TCPClient=TCPClient()
tcpClient.fd=clientfd
tcpClient.port=Int(port)
if let addr=String(cString: buff, encoding: String.Encoding.utf8){
tcpClient.addr=addr
}
return tcpClient
}
return nil
}
open func close()->(Bool,String){
if let fd:Int32=self.fd{
c_ytcpsocket_close(fd)
self.fd=nil
return (true,"close success")
}else{
return (false,"socket not open")
}
}
}
|
mit
|
043ee0a9217f2107cb232175812c89dd
| 34.762162 | 137 | 0.604444 | 3.949851 | false | false | false | false |
uasys/swift
|
test/SILGen/default_arguments_serialized.swift
|
3
|
3810
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/default_arguments_other.swiftmodule -emit-module -swift-version 4 -primary-file %S/Inputs/default_arguments_other.swift
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=SWIFT3 --check-prefix=CHECK
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=SWIFT4 --check-prefix=CHECK
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=OPT
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=OPT
// Check that default arguments are serialized in Swift 4 mode.
import default_arguments_other
// CHECK-LABEL: sil @_T028default_arguments_serialized0A6StringSSyF : $@convention(thin) () -> @owned String
public func defaultString() -> String { return "hi" }
// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
public func hasDefaultArguments(x: Int = 0, y: String = defaultString()) {}
// CHECK-LABEL: sil @_T028default_arguments_serialized21callsDefaultArgumentsyyF : $@convention(thin) () -> ()
// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytF : $@convention(thin) (Int, @owned String) -> ()
// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
// CHECK: apply
// CHECK: return
public func callsDefaultArguments() {
hasDefaultArguments()
}
// When calling a default argument generator for a function in another module
// that was built in Swift 4 mode, we should always treat it as serialized,
// even if *this* module is built in Swift 3 mode.
// CHECK-LABEL: sil @_T028default_arguments_serialized26callsOtherDefaultArgumentsyyF : $@convention(thin) () -> ()
// CHECK: function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> ()
// CHECK: function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tFfA_ : $@convention(thin) () -> Int
// CHECK: apply
// CHECK: return
// Make sure the optimizer inlines the default argument generator from the
// other module.
// OPT-LABEL: sil @_T028default_arguments_serialized26callsOtherDefaultArgumentsyyF : $@convention(thin) () -> ()
// OPT: [[FN:%.*]] = function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> () // user: %3
// OPT: [[INT_VAL:%.*]] = integer_literal [[INT_TYPE:\$Builtin.Int(32|64)]], 0
// OPT: [[INT:%.*]] = struct $Int ([[INT_VAL]] : [[INT_TYPE]]
// OPT: apply [[FN]]([[INT]]) : $@convention(thin) (Int) -> ()
// OPT: return
public func callsOtherDefaultArguments() {
otherDefaultArguments()
}
// CHECK-LABEL: sil @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> ()
// CHECK-LABEL: sil [serialized] @_T023default_arguments_other0C16DefaultArgumentsySi1x_tFfA_ : $@convention(thin) () -> Int
|
apache-2.0
|
6a9c3889b5b17287d8e95a2a3adc4f05
| 62.5 | 176 | 0.731496 | 3.38968 | false | false | false | false |
akolov/GoldenTiler
|
GoldenSpiralFilter/GoldenSpiralFilter/UIImage+Metal.swift
|
1
|
682
|
//
// UIImage+Metal.swift
// GoldenTiler
//
// Created by Alexander Kolov on 10/6/15.
// Copyright © 2015 Alexander Kolov. All rights reserved.
//
import Metal
import UIKit
public extension UIImage {
public func imageByConvertingFromCIImage(device device: MTLDevice? = nil, context: CIContext? = nil) -> UIImage? {
if CGImage != nil {
return self
}
guard let image = self.CIImage else {
return nil
}
guard let device = device ?? MTLCreateSystemDefaultDevice() else {
return nil
}
let context = context ?? CIContext(MTLDevice: device)
return UIImage(CGImage: context.createCGImage(image, fromRect: image.extent))
}
}
|
mit
|
5bf1b0e0387407eb7acb0b352996b53e
| 20.967742 | 116 | 0.674009 | 4.077844 | false | false | false | false |
sonsongithub/reddift
|
application/ImageViewPageController.swift
|
1
|
8079
|
//
// ImageViewPageController.swift
// UZImageCollection
//
// Created by sonson on 2015/06/08.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import UIKit
protocol Page {
var index: Int { get }
var isOpenedBy3DTouch: Bool { get set }
var alphaWithoutMainContent: CGFloat { get set }
}
let ImageViewPageControllerDidChangePageName = Notification.Name(rawValue: "ImageViewPageControllerDidChangePageName")
let ImageViewPageControllerDidStartDraggingThumbnailName = Notification.Name(rawValue: "ImageViewPageControllerDidStartDraggingThumbnailName")
class ImageViewPageController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIGestureRecognizerDelegate {
var thumbnails: [Thumbnail] = []
var currentIndex = 0
var imageViewController: ImageViewDestination?
let navigationBar = UINavigationBar(frame: CGRect.zero)
let item: UINavigationItem = UINavigationItem(title: "")
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
view.backgroundColor = UIColor.white
navigationBar.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(navigationBar)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[navigationBar]-0-|", options: NSLayoutFormatOptions(), metrics: [:], views: ["navigationBar": navigationBar]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[navigationBar(==64)]", options: NSLayoutFormatOptions(), metrics: [:], views: ["navigationBar": navigationBar]))
navigationBar.pushItem(item, animated: false)
navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ImageViewPageController.close(sender:)))
isNavigationBarHidden = true
}
var _alphaWithoutMainContent: CGFloat = 1
var alphaWithoutMainContent: CGFloat {
get {
return _alphaWithoutMainContent
}
set {
navigationBar.alpha = newValue
_alphaWithoutMainContent = newValue
view.backgroundColor = view.backgroundColor?.withAlphaComponent(_alphaWithoutMainContent)
guard var pages = self.viewControllers?.compactMap({ $0 as? Page}) else { return }
for i in 0..<pages.count {
pages[i].alphaWithoutMainContent = _alphaWithoutMainContent
}
}
}
func setOffset() {
let offset = CGFloat(0)
if let controllers = self.viewControllers {
for item in controllers {
if let controller = item as? ImageViewController {
controller.scrollView.contentInset = UIEdgeInsets(top: offset, left: 0, bottom: 0, right: 0)
}
}
}
}
var isNavigationBarHidden: Bool = false {
didSet {
navigationBar.isHidden = isNavigationBarHidden
let offset = isNavigationBarHidden ? CGFloat(-44) : CGFloat(0)
if let controllers = self.viewControllers {
for item in controllers {
if let controller = item as? ImageViewController {
controller.scrollView.contentInset = UIEdgeInsets(top: offset, left: 0, bottom: 0, right: 0)
}
}
}
}
}
@objc func close(sender: Any) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
init(thumbnails: [Thumbnail], index: Int) {
self.thumbnails = thumbnails
self.currentIndex = index
super.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey: 12])
self.dataSource = self
self.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(ImageViewPageController.didMoveCurrentImage(notification:)), name: ImageViewControllerDidChangeCurrentImageName, object: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(self, selector: #selector(ImageViewPageController.didMoveCurrentImage(notification:)), name: ImageViewControllerDidChangeCurrentImageName, object: nil)
}
class func controller(thumbnails: [Thumbnail], index: Int, isOpenedBy3DTouch: Bool) -> ImageViewPageController {
let vc = ImageViewPageController(thumbnails: thumbnails, index: index)
var con: UIViewController? = nil
switch thumbnails[index] {
case .Image:
con = ImageViewController(index: index, thumbnails: thumbnails, isOpenedBy3DTouch: isOpenedBy3DTouch)
case .Movie:
con = MoviePlayerController(index: index, thumbnails: thumbnails, isOpenedBy3DTouch: isOpenedBy3DTouch)
}
if let destination = con as? ImageViewDestination {
vc.imageViewController = destination
}
vc.currentIndex = index
vc.setTitle(string: thumbnails[index].url.absoluteString)
if let con = con {
vc.setViewControllers([con], direction: .forward, animated: false, completion: { (_) -> Void in })
}
return vc
}
func setTitle(string: String) {
let rect = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44)
let label = UILabel(frame: rect)
label.text = string
label.numberOfLines = 3
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
item.titleView = label
}
@objc func didMoveCurrentImage(notification: NSNotification) {
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let controller = pageViewController.viewControllers?.last as? ImageViewDestination {
self.imageViewController = controller
}
if let viewController = pageViewController.viewControllers?.last as? Page {
let index = viewController.index
currentIndex = index
setTitle(string: thumbnails[index].url.absoluteString)
let userInfo: [String: Any] = ["index": index, "thumbnail": thumbnails[index]]
NotificationCenter.default.post(name: ImageViewPageControllerDidChangePageName, object: nil, userInfo: userInfo)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? Page {
let index = viewController.index + 1
if thumbnails.count <= index {
return nil
}
switch self.thumbnails[index] {
case .Image:
return ImageViewController(index: index, thumbnails: self.thumbnails)
case .Movie:
return MoviePlayerController(index: index, thumbnails: self.thumbnails)
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? Page {
let index = viewController.index - 1
if index < 0 {
return nil
}
switch self.thumbnails[index] {
case .Image:
return ImageViewController(index: index, thumbnails: self.thumbnails)
case .Movie:
return MoviePlayerController(index: index, thumbnails: self.thumbnails)
}
}
return nil
}
}
|
mit
|
eb46d856219367011e0c117922976657
| 41.962766 | 218 | 0.658165 | 5.528405 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/Networking/MediaHost+ReaderPostContentProvider.swift
|
1
|
1865
|
import Foundation
/// Extends `MediaRequestAuthenticator.MediaHost` so that we can easily
/// initialize it from a given `Blog`.
///
extension MediaHost {
enum ReaderPostContentProviderError: Swift.Error {
case noDefaultWordPressComAccount
case baseInitializerError(error: Error, readerPostContentProvider: ReaderPostContentProvider)
}
init(with readerPostContentProvider: ReaderPostContentProvider, failure: (ReaderPostContentProviderError) -> ()) {
let isAccessibleThroughWPCom = readerPostContentProvider.isWPCom() || readerPostContentProvider.isJetpack()
// This is the only way in which we can obtain the username and authToken here.
// It'd be nice if all data was associated with an account instead, for transparency
// and cleanliness of the code - but this'll have to do for now.
let accountService = AccountService(managedObjectContext: ContextManager.shared.mainContext)
// We allow a nil account in case the user connected only self-hosted sites.
let account = accountService.defaultWordPressComAccount()
let username = account?.username
let authToken = account?.authToken
self.init(isAccessibleThroughWPCom: isAccessibleThroughWPCom,
isPrivate: readerPostContentProvider.isPrivate(),
isAtomic: readerPostContentProvider.isAtomic(),
siteID: readerPostContentProvider.siteID()?.intValue,
username: username,
authToken: authToken,
failure: { error in
// We just associate a ReaderPostContentProvider with the underlying error for simpler debugging.
failure(ReaderPostContentProviderError.baseInitializerError(
error: error,
readerPostContentProvider: readerPostContentProvider))
})
}
}
|
gpl-2.0
|
588cd0c3a9101869bb818dbfc6f2b735
| 48.078947 | 118 | 0.70563 | 5.93949 | false | false | false | false |
TellMeAMovieTeam/TellMeAMovie_iOSApp
|
TellMeAMovie/Pods/TMDBSwift/Sources/Models/ListsMDB.swift
|
1
|
1451
|
//
// ListMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-03-08.
// Copyright © 2016 George KyeKye. All rights reserved.
//
import Foundation
///TODO: ListItem status
public struct ListsMDB: ArrayObject{
public var created_by: String!
public var description: String?
public var favorite_count: Int!
public var id: String!
public var items = [MovieMDB]()
public var item_count: Int!
public var iso_639_1: String!
public var name: String!
public var poster_path: String?
public init(results: JSON){
created_by = results["created_by"].string
description = results["description"].string
favorite_count = results["favorite_count"].int
id = results["id"].string
items = MovieMDB.initialize(json: results["items"])
item_count = results["items_count"].int
iso_639_1 = results["iso_639_1"].string
name = results["name"].string
poster_path = results["poster_path"].string
}
///MARK: Lists
public static func lists(_ api_key: String!, listId: String!, completion: @escaping (_ clientReturn: ClientReturn, _ data: ListsMDB?) -> ()) -> (){
let url = "https://api.themoviedb.org/3/list/" + listId
Client.Lists(url, api_key: api_key, listId: listId!){
apiReturn in
if(apiReturn.error == nil){
completion(apiReturn, ListsMDB.init(results: apiReturn.json!))
}else{
completion(apiReturn, nil)
}
}
}
}
|
apache-2.0
|
af317385aed3f84142312cf72363559a
| 27.431373 | 150 | 0.650345 | 3.717949 | false | false | false | false |
Incipia/Goalie
|
PaintCode/WaterBottleAccessoryKit.swift
|
1
|
6011
|
//
// WaterBottleAccessoryKit.swift
// Goalie
//
// Created by Gregory Klein on 3/28/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import Foundation
class WaterBottleAccessoryKit: AccessoryItemDrawing
{
static func drawWithFrame(_ frame: CGRect, priority: TaskPriority)
{
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
// let primaryColor = UIColor(red: 0.072, green: 0.412, blue: 0.759, alpha: 1.000)
let primaryColor = UIColor(priority: priority, headComponent: .background)
//// Subframes
let group2: CGRect = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height)
//// Group 2
//// Group
context!.saveGState()
context!.setAlpha(0.4)
context!.beginTransparencyLayer(auxiliaryInfo: nil)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: group2.minX + 0.60055 * group2.width, y: group2.minY + 0.63947 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.54859 * group2.width, y: group2.minY + 0.65957 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.58655 * group2.width, y: group2.minY + 0.64822 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.56877 * group2.width, y: group2.minY + 0.65525 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.38091 * group2.width, y: group2.minY + 0.58137 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.45455 * group2.width, y: group2.minY + 0.67967 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.37518 * group2.width, y: group2.minY + 0.63107 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.52691 * group2.width, y: group2.minY + 0.47302 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.38636 * group2.width, y: group2.minY + 0.53420 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.46105 * group2.width, y: group2.minY + 0.49580 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.54077 * group2.width, y: group2.minY + 0.47752 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.53309 * group2.width, y: group2.minY + 0.47090 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.54064 * group2.width, y: group2.minY + 0.47337 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.62355 * group2.width, y: group2.minY + 0.56755 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.54214 * group2.width, y: group2.minY + 0.51302 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.59864 * group2.width, y: group2.minY + 0.53715 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.60055 * group2.width, y: group2.minY + 0.63947 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.64400 * group2.width, y: group2.minY + 0.59250 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.63150 * group2.width, y: group2.minY + 0.62015 * group2.height))
bezierPath.close()
bezierPath.move(to: CGPoint(x: group2.minX + 0.69127 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezierPath.addLine(to: CGPoint(x: group2.minX + 0.30873 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.00000 * group2.width, y: group2.minY + 0.32075 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.13823 * group2.width, y: group2.minY + 0.15000 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.00000 * group2.width, y: group2.minY + 0.22287 * group2.height))
bezierPath.addLine(to: CGPoint(x: group2.minX + 0.00000 * group2.width, y: group2.minY + 1.00000 * group2.height))
bezierPath.addLine(to: CGPoint(x: group2.minX + 1.00000 * group2.width, y: group2.minY + 1.00000 * group2.height))
bezierPath.addLine(to: CGPoint(x: group2.minX + 1.00000 * group2.width, y: group2.minY + 0.32075 * group2.height))
bezierPath.addCurve(to: CGPoint(x: group2.minX + 0.69127 * group2.width, y: group2.minY + 0.15000 * group2.height), controlPoint1: CGPoint(x: group2.minX + 1.00000 * group2.width, y: group2.minY + 0.22287 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.86177 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezierPath.close()
primaryColor.setFill()
bezierPath.fill()
context!.endTransparencyLayer()
context!.restoreGState()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: group2.minX + 0.72726 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezier2Path.addLine(to: CGPoint(x: group2.minX + 0.27271 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezier2Path.addLine(to: CGPoint(x: group2.minX + 0.27271 * group2.width, y: group2.minY + 0.06675 * group2.height))
bezier2Path.addCurve(to: CGPoint(x: group2.minX + 0.41280 * group2.width, y: group2.minY + 0.00000 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.27271 * group2.width, y: group2.minY + 0.02988 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.34576 * group2.width, y: group2.minY + 0.00000 * group2.height))
bezier2Path.addLine(to: CGPoint(x: group2.minX + 0.58717 * group2.width, y: group2.minY + 0.00000 * group2.height))
bezier2Path.addCurve(to: CGPoint(x: group2.minX + 0.72726 * group2.width, y: group2.minY + 0.06675 * group2.height), controlPoint1: CGPoint(x: group2.minX + 0.65421 * group2.width, y: group2.minY + 0.00000 * group2.height), controlPoint2: CGPoint(x: group2.minX + 0.72726 * group2.width, y: group2.minY + 0.02988 * group2.height))
bezier2Path.addLine(to: CGPoint(x: group2.minX + 0.72726 * group2.width, y: group2.minY + 0.15000 * group2.height))
bezier2Path.close()
primaryColor.setFill()
bezier2Path.fill()
}
}
|
apache-2.0
|
e595532bff0663be5b5d8ae6cd9808ac
| 81.328767 | 336 | 0.683361 | 3.052311 | false | false | false | false |
Aahung/two-half-password
|
two-half-password/Models/VaultItem.swift
|
1
|
2847
|
//
// VaultItem.swift
// two-half-password
//
// Created by Xinhong LIU on 15/6/15.
// Copyright © 2015 ParseCool. All rights reserved.
//
import Cocoa
class VaultItem: NSObject {
var vault: Vault
var identifier: String!
var type: String!
var title: String!
var urlString: String!
enum VaultItemError {
enum LoadContentError: ErrorType {
case FailLoadFile
case InvalidFile
}
enum DecryptError: ErrorType {
case VaultLocked
}
}
init(vault: Vault, array: NSArray) throws {
self.vault = vault
identifier = array[0] as! String
type = array[1] as! String
title = array[2] as! String
urlString = array[3] as! String
}
func dataPath() -> String {
return "\(vault.mainDirectoryPath())/\(identifier).1password"
}
// return encrypted dictionary
func loadContents() throws -> NSDictionary {
let data = NSData(contentsOfFile: dataPath())
guard (data != nil) else {
throw VaultItemError.LoadContentError.FailLoadFile
}
var dictionary: NSDictionary!
do {
dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
} catch {
throw VaultItemError.LoadContentError.InvalidFile
}
return dictionary
}
// return decrypted dictionary
func info() throws -> NSDictionary {
let mutableDictionary = NSMutableDictionary(dictionary: try loadContents())
// decode base64
guard (mutableDictionary["encrypted"] != nil) else {
throw VaultItemError.LoadContentError.InvalidFile
}
let encryptedData = NSData(base64EncodedString: mutableDictionary["encrypted"] as! String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let (salt, cipher) = Crypto.extractSaltAndCipher(encryptedData!)
guard (vault.unlocked()) else {
throw VaultItemError.DecryptError.VaultLocked
}
let (aesKey, iv) = Crypto.OpenSSLKey(vault.encryptionKey!, salt: salt)
let decryptedData = Crypto.AES128Decrypt(aesKey, encryptedKey: cipher, iv: iv)
var decryptedDictionary: NSDictionary!
do {
decryptedDictionary = try NSJSONSerialization.JSONObjectWithData(decryptedData, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
} catch {
throw VaultItemError.LoadContentError.InvalidFile
}
mutableDictionary.setValue(decryptedDictionary, forKey: "decrypted")
return mutableDictionary
}
}
|
mit
|
dbfde8685932265c1b1218add327a6c4
| 28.957895 | 160 | 0.614195 | 5.109515 | false | false | false | false |
paulyoung/Ogra
|
Ogra/Encodable.swift
|
1
|
3272
|
//
// Encodable.swift
// Ogra
//
// Created by Craig Edwards on 27/07/2015.
// Copyright © 2015 Craig Edwards. All rights reserved.
//
import Foundation
import Argo
public protocol Encodable {
func encode() -> JSON
}
extension JSON: Encodable {
public func encode() -> JSON {
return self
}
}
extension String: Encodable {
public func encode() -> JSON {
return .String(self)
}
}
extension Bool: Encodable {
public func encode() -> JSON {
return .Number(self ? 1 : 0)
}
}
extension Int: Encodable {
public func encode() -> JSON {
return .Number(self)
}
}
extension Double: Encodable {
public func encode() -> JSON {
return .Number(self)
}
}
extension Float: Encodable {
public func encode() -> JSON {
return .Number(self)
}
}
extension UInt: Encodable {
public func encode() -> JSON {
return .Number(self)
}
}
extension Optional where Wrapped: Encodable {
public func encode() -> JSON {
switch self {
case .None: return .Null
case .Some(let v): return v.encode()
}
}
}
extension CollectionType where Self: DictionaryLiteralConvertible, Self.Key: StringLiteralConvertible, Self.Value: Encodable, Generator.Element == (Self.Key, Self.Value) {
public func encode() -> JSON {
var values = [String : JSON]()
for (key, value) in self {
values[String(key)] = value.encode()
}
return .Object(values)
}
}
extension Optional where Wrapped: protocol<CollectionType, DictionaryLiteralConvertible>, Wrapped.Key: StringLiteralConvertible, Wrapped.Value: Encodable, Wrapped.Generator.Element == (Wrapped.Key, Wrapped.Value) {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .Null
}
}
extension CollectionType where Generator.Element: Encodable {
public func encode() -> JSON {
return JSON.Array(self.map { $0.encode() })
}
}
extension Optional where Wrapped: CollectionType, Wrapped.Generator.Element: Encodable {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .Null
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == String {
public func encode() -> JSON {
return .String(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Int {
public func encode() -> JSON {
return .Number(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Double {
public func encode() -> JSON {
return .Number(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Float {
public func encode() -> JSON {
return .Number(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == UInt {
public func encode() -> JSON {
return .Number(self.rawValue)
}
}
extension JSON {
public func JSONObject() -> AnyObject {
switch self {
case .Null: return NSNull()
case .String(let value): return value
case .Number(let value): return value
case .Array(let array): return array.map { $0.JSONObject() }
case .Object(let object):
var dict: [Swift.String : AnyObject] = [:]
for key in object.keys {
if let value = object[key] {
dict[key] = value.JSONObject()
} else {
dict[key] = NSNull()
}
}
return dict
}
}
}
|
mit
|
915aab774b518d3ee85a06515d504eaa
| 21.715278 | 214 | 0.666157 | 3.574863 | false | false | false | false |
fleurdeswift/extra-appkit
|
ExtraAppKit/FilterableOutlineView.swift
|
1
|
2726
|
//
// FilterableOutlineView.swift
// ExtraAppKit
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Cocoa
public typealias PredicateBlockType = (object: AnyObject) -> Bool;
@objc
public protocol FilterablePredicateGenerator {
func generatePredicateFromString(string: String?) -> PredicateBlockType?;
}
public class FilterableOutlineView : NSOutlineView {
private var filterDataSource: FilterableDataSource?;
private var prefilterState: OutlineViewState?;
public override func reloadData() {
if let filterDataSource = self.filterDataSource {
filterDataSource.reloadData(self)
}
super.reloadData()
}
public override func setDataSource(dataSource: NSOutlineViewDataSource?) {
if let dataSource = dataSource {
filterDataSource = FilterableDataSource(dataSource: dataSource);
filterDataSource!.setFilterPredicate(_filterPredicate, outlineView: self)
}
else {
filterDataSource = nil;
}
super.setDataSource(filterDataSource)
}
private var _filterPredicate: PredicateBlockType?;
public var filterPredicate: PredicateBlockType? {
get {
return _filterPredicate;
}
set {
if _filterPredicate == nil {
prefilterState = self.state;
}
_filterPredicate = newValue;
if let dataSource = filterDataSource {
dataSource.setFilterPredicate(newValue, outlineView: self);
}
super.reloadData();
if newValue != nil {
self.expandItem(nil, expandChildren: true);
if let state = prefilterState {
self.selectionState = state.selectionState;
}
}
else if let state = prefilterState {
self.state = state;
prefilterState = nil;
}
}
}
@IBOutlet
public weak var predicateGenerator: FilterablePredicateGenerator?;
@IBAction
public func setSearchString(sender: AnyObject?) {
if let field = sender as? NSControl {
self.filterPredicate = predicateGenerator?.generatePredicateFromString(field.stringValue);
}
else {
self.filterPredicate = nil;
}
}
@objc
public override func awakeFromNib() {
super.awakeFromNib()
if predicateGenerator == nil {
predicateGenerator = filterDataSource?.dataSource as? FilterablePredicateGenerator;
}
}
}
|
mit
|
9aa0099c054c1fa9260c7343a5d75334
| 27.385417 | 102 | 0.586789 | 5.72479 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.