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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PrashntS/sleepygeeks | Sleepy/Sleepy/ModelController.swift | 1 | 3243 | //
// ModelController.swift
// Sleepy
//
// Created by Prashant Sinha on 18/01/15.
// Copyright (c) 2015 Prashant Sinha. All rights reserved.
//
import UIKit
/*
A controller object that manages a simple model -- a collection of month names.
The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:.
It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application.
There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand.
*/
class ModelController: NSObject, UIPageViewControllerDataSource {
var pageData = NSArray()
override init() {
super.init()
// Create the data model.
let dateFormatter = NSDateFormatter()
pageData = dateFormatter.monthSymbols
}
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? {
// Return the data view controller for the given index.
if (self.pageData.count == 0) || (index >= self.pageData.count) {
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as DataViewController
dataViewController.dataObject = self.pageData[index]
return dataViewController
}
func indexOfViewController(viewController: DataViewController) -> Int {
// Return the index of the given data view controller.
// For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index.
if let dataObject: AnyObject = viewController.dataObject {
return self.pageData.indexOfObject(dataObject)
} else {
return NSNotFound
}
}
// MARK: - Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as DataViewController)
if (index == 0) || (index == NSNotFound) {
return nil
}
index--
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as DataViewController)
if index == NSNotFound {
return nil
}
index++
if index == self.pageData.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
}
| mit | 3fb2bf2b97bea7786728da74f86139a3 | 39.037037 | 225 | 0.709837 | 5.66958 | false | false | false | false |
1aurabrown/eidolon | Kiosk/Bid Fulfillment/Models/BidDetails.swift | 1 | 542 | @objc class BidDetails: NSObject {
dynamic var newUser: NewUser = NewUser()
dynamic var saleArtwork: SaleArtwork?
dynamic var bidderNumber: String?
dynamic var bidderPIN: String?
dynamic var bidAmountCents: NSNumber?
dynamic var bidderID: String?
init(saleArtwork: SaleArtwork?, bidderNumber: String?, bidderPIN: String?, bidAmountCents:Int?) {
self.saleArtwork = saleArtwork
self.bidderNumber = bidderNumber
self.bidderPIN = bidderPIN
self.bidAmountCents = bidAmountCents
}
} | mit | 79c237bf7ffcb39755f3e46c0468ccb8 | 32.9375 | 101 | 0.706642 | 4.79646 | false | false | false | false |
chanhx/Octogit | iGithub/Models/Event.swift | 2 | 8305 |
//
// Event.swift
// iGithub
//
// Created by Chan Hocheung on 7/21/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import Foundation
import ObjectMapper
import SwiftDate
enum EventType: String {
case commitCommentEvent = "CommitCommentEvent"
case createEvent = "CreateEvent"
case deleteEvent = "DeleteEvent"
case deploymentEvent = "DeploymentEvent" // not visible
case deploymentStatusEvent = "DeploymentStatusEvent" // not visible
case downloadEvent = "DownloadEvent" // no longer created
case followEvent = "FollowEvent" // no longer created
case forkEvent = "ForkEvent"
case forkApplyEvent = "ForkApplyEvent" // no longer created
case gistEvent = "GistEvent" // no longer created
case gollumEvent = "GollumEvent"
case issueCommentEvent = "IssueCommentEvent"
case issuesEvent = "IssuesEvent"
case memberEvent = "MemberEvent"
case membershipEvent = "MembershipEvent" // not visible
case pageBuildEvent = "PageBuildEvent" // not visible
case publicEvent = "PublicEvent"
case pullRequestEvent = "PullRequestEvent"
case pullRequestReviewCommentEvent = "PullRequestReviewCommentEvent"
case pushEvent = "PushEvent"
case releaseEvent = "ReleaseEvent"
case repositoryEvent = "RepositoryEvent" // not visible
case statusEvent = "StatusEvent" // not visible
case teamAddEvent = "TeamAddEvent"
case watchEvent = "WatchEvent"
}
class Event: Mappable, StaticMappable {
var id: Int?
var type: EventType?
var repository: String?
var actor: User?
var org: User?
var createdAt: Date?
static func objectForMapping(map: ObjectMapper.Map) -> BaseMappable? {
if let type: EventType = EventType(rawValue: map["type"].value()!) {
switch type {
case .commitCommentEvent: return CommitCommentEvent(map: map)
case .createEvent: return CreateEvent(map: map)
case .deleteEvent: return DeleteEvent(map: map)
case .forkEvent: return ForkEvent(map: map)
case .gollumEvent: return GollumEvent(map: map)
case .issueCommentEvent: return IssueCommentEvent(map: map)
case .issuesEvent: return IssueEvent(map: map)
case .memberEvent: return MemberEvent(map: map)
case .publicEvent: return PublicEvent(map: map)
case .pullRequestEvent: return PullRequestEvent(map: map)
case .pullRequestReviewCommentEvent: return PullRequestReviewCommentEvent(map: map)
case .pushEvent: return PushEvent(map: map)
case .releaseEvent: return ReleaseEvent(map: map)
case .watchEvent: return WatchEvent(map: map)
default: return nil
}
}
return nil
}
required init?(map: Map) {
mapping(map: map)
}
func mapping(map: Map) {
id <- (map["id"], IntTransform())
type <- map["type"]
repository <- map["repo.name"]
actor <- map["actor"]
org <- map["org"]
createdAt <- (map["created_at"], ISO8601DateTransform())
}
}
// MARK: CommitCommentEvent
class CommitCommentEvent : Event {
var comment: CommitComment?
override func mapping(map: Map) {
super.mapping(map: map)
comment <- map["payload.comment"]
}
}
enum RefType : String {
case branch = "branch"
case tag = "tag"
case repository = "repository"
}
// MARK: CreateEvent
class CreateEvent: Event {
var refType: RefType?
var ref: String?
var repoDescription: String?
override func mapping(map: Map) {
super.mapping(map: map)
refType <- map["payload.ref_type"]
ref <- map["payload.ref"]
repoDescription <- map["payload.description"]
}
}
// MARK: DeleteEvent
class DeleteEvent: Event {
var refType: RefType?
var ref: String?
override func mapping(map: Map) {
super.mapping(map: map)
refType <- map["payload.ref_type"]
ref <- map["payload.ref"]
}
}
// MARK: ForkEvent
class ForkEvent: Event {
var forkee: String?
var forkeeDescription: String?
override func mapping(map: Map) {
super.mapping(map: map)
forkee <- map["payload.forkee.full_name"]
forkeeDescription <- map["payload.forkee.description"]
}
}
// MARK: GollumEvent
class GollumEvent: Event {
var pageName: String?
var action: String?
var summary: String?
override func mapping(map: Map) {
super.mapping(map: map)
pageName <- map["payload.pages.0.page_name"]
action <- map["payload.pages.0.action"]
summary <- map["payload.pages.0.summary"]
}
}
// MARK: IssueCommentEvent
class IssueCommentEvent : Event {
var action: String?
var issue: Issue?
var comment: String?
override func mapping(map: Map) {
super.mapping(map: map)
action <- map["payload.action"]
issue <- map["payload.issue"]
comment <- map["payload.comment.body"]
}
}
// MARK: IssueEvent
enum IssueAction: String {
case assigned = "assigned"
case unassigned = "unassigned"
case labeled = "labeled"
case unlabeled = "unlabeled"
case opened = "opened"
case edited = "edited"
case closed = "closed"
case reopened = "reopened"
}
class IssueEvent: Event {
var issue: Issue?
var action: IssueAction?
override func mapping(map: Map) {
super.mapping(map: map)
issue <- map["payload.issue"]
action <- map["payload.action"]
}
}
// MARK: MemberEvent
class MemberEvent: Event {
var member: User?
override func mapping(map: Map) {
super.mapping(map: map)
member <- map["payload.member"]
}
}
// MARK: PublicEvent
class PublicEvent: Event {
var repositoryDescription: String?
override func mapping(map: Map) {
super.mapping(map: map)
repositoryDescription <- map["payload.repository.description"]
}
}
// MARK: PullRequestEvent
class PullRequestEvent : Event {
var pullRequest: PullRequest?
var action: IssueAction?
override func mapping(map: Map) {
super.mapping(map: map)
pullRequest <- map["payload.pull_request"]
action <- map["payload.action"]
}
}
// MARK: PullRequestCommentEvent
class PullRequestReviewCommentEvent : Event {
var action: String?
var pullRequest : PullRequest?
var comment: String?
override func mapping(map: Map) {
super.mapping(map: map)
action <- map["payload.action"]
pullRequest <- map["payload.pull_request"]
comment <- map["payload.comment.body"]
}
}
// MARK: PushEvent
class PushEvent : Event {
var ref: String?
var commitCount: Int?
var distinctCommitCount: Int?
var previousHeadSHA: String?
var currentHeadSHA: String?
var branchName: String?
var commits: [EventCommit]?
override func mapping(map: Map) {
super.mapping(map: map)
ref <- map["payload.ref"]
commitCount <- map["payload.size"]
distinctCommitCount <- map["payload.distinct_size"]
previousHeadSHA <- map["payload.before"]
currentHeadSHA <- map["payload.head"]
branchName <- map["payload.ref"]
commits <- map["payload.commits"]
}
}
// MARK: ReleaseEvent
class ReleaseEvent: Event {
var releaseTagName: String?
override func mapping(map: Map) {
super.mapping(map: map)
releaseTagName <- map["payload.release.tag_name"]
}
}
// MARK: WatchEvent
class WatchEvent : Event {
var action: String?
override func mapping(map: Map) {
super.mapping(map: map)
action <- map["payload.action"]
}
}
| gpl-3.0 | de20684267b1437d98839f40e70cd04b | 25.961039 | 95 | 0.592606 | 4.379747 | false | false | false | false |
ptankTwilio/video-quickstart-swift | VideoCallKitQuickStart/ViewController.swift | 1 | 14186 | //
// ViewController.swift
// VideoCallKitQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
import CallKit
class ViewController: UIViewController {
// MARK: View Controller Members
// Configure access token manually for testing, if desired! Create one manually in the console
// at https://www.twilio.com/user/account/video/dev-tools/testing-tools
var accessToken = "TWILIO_ACCESS_TOKEN"
// Configure remote URL to fetch token from
var tokenUrl = "http://localhost:8000/token.php"
// Video SDK components
var room: TVIRoom?
var camera: TVICameraCapturer?
var localVideoTrack: TVILocalVideoTrack?
var localAudioTrack: TVILocalAudioTrack?
var participant: TVIParticipant?
var remoteView: TVIVideoView?
// CallKit components
let callKitProvider:CXProvider
let callKitCallController:CXCallController
var callKitCompletionHandler: ((Bool)->Swift.Void?)? = nil
// MARK: UI Element Outlets and handles
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var simulateIncomingButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var roomTextField: UITextField!
@IBOutlet weak var roomLine: UIView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var micButton: UIButton!
// `TVIVideoView` created from a storyboard
@IBOutlet weak var previewView: TVIVideoView!
required init?(coder aDecoder: NSCoder) {
let configuration = CXProviderConfiguration(localizedName: "CallKit Quickstart")
configuration.maximumCallGroups = 1
configuration.maximumCallsPerCallGroup = 1
configuration.supportsVideo = true
if let callKitIcon = UIImage(named: "iconMask80") {
configuration.iconTemplateImageData = UIImagePNGRepresentation(callKitIcon)
}
callKitProvider = CXProvider(configuration: configuration)
callKitCallController = CXCallController()
super.init(coder: aDecoder)
callKitProvider.setDelegate(self, queue: nil)
}
deinit {
// CallKit has an odd API contract where the developer must call invalidate or the CXProvider is leaked.
callKitProvider.invalidate()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if PlatformUtils.isSimulator {
self.previewView.removeFromSuperview()
} else {
// Preview our local camera track in the local video preview view.
self.startPreview()
}
// Disconnect and mic button will be displayed when the Client is connected to a Room.
self.disconnectButton.isHidden = true
self.micButton.isHidden = true
self.roomTextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
func setupRemoteVideoView() {
// Creating `TVIVideoView` programmatically
self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate: self)
self.view.insertSubview(self.remoteView!, at: 0)
// `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit
// scaleAspectFit is the default mode when you create `TVIVideoView` programmatically.
self.remoteView!.contentMode = .scaleAspectFit;
let centerX = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerY)
let width = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0);
self.view.addConstraint(width)
let height = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 1,
constant: 0);
self.view.addConstraint(height)
}
// MARK: IBActions
@IBAction func connect(sender: AnyObject) {
performStartCallAction(uuid: UUID.init(), roomName: self.roomTextField.text)
self.dismissKeyboard()
}
@IBAction func disconnect(sender: AnyObject) {
if let room = room, let uuid = room.uuid {
logMessage(messageText: "Attempting to disconnect from room \(room.name)")
performEndCallAction(uuid: uuid)
}
}
@IBAction func toggleMic(sender: AnyObject) {
if (self.localAudioTrack != nil) {
self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)!
// Update the button title
if (self.localAudioTrack?.isEnabled == true) {
self.micButton.setTitle("Mute", for: .normal)
} else {
self.micButton.setTitle("Unmute", for: .normal)
}
}
}
// MARK: Private
func startPreview() {
if PlatformUtils.isSimulator {
return
}
// Preview our local camera track in the local video preview view.
camera = TVICameraCapturer(source: .frontCamera, delegate: self)
localVideoTrack = TVILocalVideoTrack.init(capturer: camera!)
if (localVideoTrack == nil) {
logMessage(messageText: "Failed to create video track")
} else {
// Add renderer to video track for local preview
localVideoTrack!.addRenderer(self.previewView)
logMessage(messageText: "Video track created")
// We will flip camera on tap.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera))
self.previewView.addGestureRecognizer(tap)
}
}
func flipCamera() {
if (self.camera?.source == .frontCamera) {
self.camera?.selectSource(.backCameraWide)
} else {
self.camera?.selectSource(.frontCamera)
}
}
func prepareLocalMedia() {
// We will share local audio and video when we connect to the Room.
// Create an audio track.
if (localAudioTrack == nil) {
localAudioTrack = TVILocalAudioTrack.init()
if (localAudioTrack == nil) {
logMessage(messageText: "Failed to create audio track")
}
}
// Create a video track which captures from the camera.
if (localVideoTrack == nil) {
self.startPreview()
}
}
// Update our UI based upon if we are in a Room or not
func showRoomUI(inRoom: Bool) {
self.connectButton.isHidden = inRoom
self.simulateIncomingButton.isHidden = inRoom
self.roomTextField.isHidden = inRoom
self.roomLine.isHidden = inRoom
self.roomLabel.isHidden = inRoom
self.micButton.isHidden = !inRoom
self.disconnectButton.isHidden = !inRoom
UIApplication.shared.isIdleTimerDisabled = inRoom
}
func dismissKeyboard() {
if (self.roomTextField.isFirstResponder) {
self.roomTextField.resignFirstResponder()
}
}
func cleanupRemoteParticipant() {
if ((self.participant) != nil) {
if ((self.participant?.videoTracks.count)! > 0) {
self.participant?.videoTracks[0].removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
self.participant = nil
}
func logMessage(messageText: String) {
NSLog(messageText)
messageLabel.text = messageText
}
func holdCall(onHold: Bool) {
localAudioTrack?.isEnabled = !onHold
localVideoTrack?.isEnabled = !onHold
}
}
// MARK: UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.connect(sender: textField)
return true
}
}
// MARK: TVIRoomDelegate
extension ViewController : TVIRoomDelegate {
func didConnect(to room: TVIRoom) {
// At the moment, this example only supports rendering one Participant at a time.
logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))")
if (room.participants.count > 0) {
self.participant = room.participants[0]
self.participant?.delegate = self
}
let cxObserver = callKitCallController.callObserver
let calls = cxObserver.calls
// Let the call provider know that the outgoing call has connected
if let uuid = room.uuid, let call = calls.first(where:{$0.uuid == uuid}) {
if call.isOutgoing {
callKitProvider.reportOutgoingCall(with: uuid, connectedAt: nil)
}
}
self.callKitCompletionHandler!(true)
}
func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))")
self.cleanupRemoteParticipant()
self.room = nil
self.showRoomUI(inRoom: false)
self.callKitCompletionHandler = nil
}
func room(_ room: TVIRoom, didFailToConnectWithError error: Error) {
logMessage(messageText: "Failed to connect to room with error: \(error.localizedDescription)")
self.callKitCompletionHandler!(false)
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) {
if (self.participant == nil) {
self.participant = participant
self.participant?.delegate = self
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) connected")
}
func room(_ room: TVIRoom, participantDidDisconnect participant: TVIParticipant) {
if (self.participant == participant) {
cleanupRemoteParticipant()
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected")
}
}
// MARK: TVIParticipantDelegate
extension ViewController : TVIParticipantDelegate {
func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) added video track")
if (self.participant == participant) {
setupRemoteVideoView()
videoTrack.addRenderer(self.remoteView!)
}
}
func participant(_ participant: TVIParticipant, removedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) removed video track")
if (self.participant == participant) {
videoTrack.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
func participant(_ participant: TVIParticipant, addedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) added audio track")
}
func participant(_ participant: TVIParticipant, removedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) removed audio track")
}
func participant(_ participant: TVIParticipant, enabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) enabled \(type) track")
}
func participant(_ participant: TVIParticipant, disabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) disabled \(type) track")
}
}
// MARK: TVIVideoViewDelegate
extension ViewController : TVIVideoViewDelegate {
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
self.view.setNeedsLayout()
}
}
// MARK: TVICameraCapturerDelegate
extension ViewController : TVICameraCapturerDelegate {
func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) {
self.previewView.shouldMirror = (source == .frontCamera)
}
}
| mit | 760dc41a301d23eddbbdc01558d63e33 | 36.036554 | 123 | 0.611843 | 5.430704 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 04-App Architecture/Swift 4/Playgrounds/Functions 2.playground/Pages/Section 3 - Generic Functions.xcplaygroundpage/Contents.swift | 2 | 1415 | //: [Previous](@previous)
import UIKit
import PlaygroundSupport
//: 
//: # Functions Part 2 - Section 3
//: Version 3 - updated for Swift 3
//:
//: 24-11-2016
//:
//: This playground is designed to support the materials of the lecure "Functions 2".
//: ## Generic Functions
//: Consider the following function
func swapInt( _ tupleValue : (Int, Int) ) -> (Int, Int) {
let y = (tupleValue.1, tupleValue.0)
return y
}
let u2 = (2,3)
let v2 = swapInt( u2 )
//: This function only works with type Int. It cannot be used for other types. This is where Generics come in. The compiler will generate alternative versions using the required types (where appropriate).
//: ### Generic Functions without constraints
func swap<U,V>( _ tupleValue : (U, V) ) -> (V, U) {
let y = (tupleValue.1, tupleValue.0)
return y
}
swap( (1, "Fred") )
//: ### Generic Functions with constraints
func compareAnything<U:Equatable>(_ a : U, b : U) -> Bool {
return a == b
}
compareAnything(10, b: 10)
//: ### Generic Functions with custom constraints
protocol CanMultiply {
static func *(left: Self, right: Self) -> Self
}
extension Double : CanMultiply {}
extension Int : CanMultiply {}
extension Float : CanMultiply {}
func cuboidVolume<T:CanMultiply>(_ width:T, _ height:T, _ depth:T) -> T {
return (width*height*depth)
}
cuboidVolume(2.1, 3.1, 4.1)
cuboidVolume(2.1, 3, 4)
| mit | 9a5f15d279a6024095b291e0044ca53b | 23.396552 | 204 | 0.669965 | 3.385167 | false | false | false | false |
wuleijun/Zeus | Zeus/ZeusAlert.swift | 1 | 3362 | //
// ZeusAlert.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/11.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class ZeusAlert {
class func alert(title title: String, message: String?, dismissTitle: String, inViewController viewController: UIViewController?, withDismissAction dismissAction: (() -> Void)?) {
dispatch_async(dispatch_get_main_queue()) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action: UIAlertAction = UIAlertAction(title: dismissTitle, style: .Default) { action -> Void in
if let dismissAction = dismissAction {
dismissAction()
}
}
alertController.addAction(action)
viewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
class func alertConfirmOrCancel(title title: String, message: String, confirmTitle: String, cancelTitle: String, inViewController viewController: UIViewController?, withConfirmAction confirmAction: () -> Void, cancelAction: () -> Void) {
dispatch_async(dispatch_get_main_queue()) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .Cancel) { action -> Void in
cancelAction()
}
alertController.addAction(cancelAction)
let confirmAction: UIAlertAction = UIAlertAction(title: confirmTitle, style: .Default) { action -> Void in
confirmAction()
}
alertController.addAction(confirmAction)
viewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
class func alertSorry(message message: String?, inViewController viewController: UIViewController?) {
alert(title: "抱歉", message: message, dismissTitle: "确定", inViewController: viewController, withDismissAction: nil)
}
}
extension UIViewController {
func alertCanNotAccessCameraRoll() {
dispatch_async(dispatch_get_main_queue()) {
ZeusAlert.alertConfirmOrCancel(title: "抱歉", message:"EMM不能访问您的相册!\n但您可以在iOS设置里修改设定。", confirmTitle: "现在就改", cancelTitle: "取消", inViewController: self, withConfirmAction: {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}, cancelAction: {
})
}
}
func alertCanNotOpenCamera() {
dispatch_async(dispatch_get_main_queue()) {
ZeusAlert.alertConfirmOrCancel(title: "抱歉", message:"EMM不能打开您的相机!\n但您可以在iOS设置里修改设定。", confirmTitle: "现在就改", cancelTitle: "取消", inViewController: self, withConfirmAction: {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}, cancelAction: {
})
}
}
}
| mit | c18282e9249dddecf02327500dc9a40d | 40.346154 | 241 | 0.619225 | 5.218447 | false | false | false | false |
lkzhao/MCollectionView | Sources/UIScrollView+Addtion.swift | 1 | 1679 | //
// UIScrollView+Addtion.swift
// MCollectionView
//
// Created by Luke on 4/16/17.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
import YetAnotherAnimationLibrary
extension UIScrollView {
public var visibleFrame: CGRect {
return bounds
}
public var visibleFrameLessInset: CGRect {
return UIEdgeInsetsInsetRect(visibleFrame, contentInset)
}
public var absoluteFrameLessInset: CGRect {
return UIEdgeInsetsInsetRect(CGRect(origin:.zero, size:bounds.size), contentInset)
}
public var innerSize: CGSize {
return absoluteFrameLessInset.size
}
public var offsetFrame: CGRect {
return CGRect(x: -contentInset.left, y: -contentInset.top,
width: max(0, contentSize.width - bounds.width + contentInset.right + contentInset.left),
height: max(0, contentSize.height - bounds.height + contentInset.bottom + contentInset.top))
}
public func absoluteLocation(for point: CGPoint) -> CGPoint {
return point - contentOffset
}
public func scrollTo(edge: UIRectEdge, animated: Bool) {
let target:CGPoint
switch edge {
case UIRectEdge.top:
target = CGPoint(x: contentOffset.x, y: offsetFrame.minY)
case UIRectEdge.bottom:
target = CGPoint(x: contentOffset.x, y: offsetFrame.maxY)
case UIRectEdge.left:
target = CGPoint(x: offsetFrame.minX, y: contentOffset.y)
case UIRectEdge.right:
target = CGPoint(x: offsetFrame.maxY, y: contentOffset.y)
default:
return
}
if animated {
yaal.contentOffset.animateTo(target)
} else {
contentOffset = target
yaal.contentOffset.updateWithCurrentState()
}
}
}
| mit | 1973af4273e01779b3a9fea6b5122f1b | 30.074074 | 110 | 0.696067 | 4.205514 | false | false | false | false |
txaidw/TWControls | TWSpriteKitUtils/TWLayout/TWCollectionNode.swift | 1 | 3132 | //
// File.swift
// Repel
//
// Created by Txai Wieser on 7/22/15.
//
//
import SpriteKit
open class TWCollectionNode: SKSpriteNode {
open fileprivate(set) var fillMode: FillMode
open fileprivate(set) var subNodes: [SKNode] = []
open var reloadCompletion: (()->())? = nil
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
public init(fillMode: FillMode) {
self.fillMode = fillMode
super.init(texture: nil, color: SKColor.clear, size: CGSize(width: fillMode.width, height: 0))
}
open func reloadCollection() {
let elements = subNodes.count
let columns = fillMode.columns
let xDiv = (fillMode.width - CGFloat(fillMode.columns)*fillMode.objectSize.width) / CGFloat(fillMode.columns-1)
let lines = Int(ceil(CGFloat(elements)/CGFloat(columns)))
var accumulatedHeight = CGFloat(0)
for lineIndex in 0..<lines {
let resta = elements - lineIndex*columns
let distance = fillMode.objectSize.height + fillMode.verticalMargin
for columnIdex in 0..<min(columns, resta) {
var xPos = (-size.width/2 + fillMode.objectSize.width/2)
xPos += CGFloat(columnIdex)*(fillMode.objectSize.width+xDiv)
let yPos = -CGFloat(lineIndex)*distance - fillMode.objectSize.height/2
subNodes[lineIndex*columns + columnIdex].position = CGPoint(x: xPos, y: yPos)
}
accumulatedHeight += distance
}
subNodes.forEach { $0.position.y += accumulatedHeight/2 - self.fillMode.verticalMargin/2 }
self.size.height = accumulatedHeight - self.fillMode.verticalMargin
reloadCompletion?()
}
open func add(node: SKNode, reload: Bool = false) {
subNodes.append(node)
self.addChild(node)
if reload {
self.reloadCollection()
}
}
open func remove(node: SKNode?, reload: Bool = false) {
if let n = node {
n.removeFromParent()
if let ind = subNodes.index(of: n) {
subNodes.remove(at: ind)
}
if reload {
self.reloadCollection()
}
}
}
public struct FillMode {
let columns: Int
let width: CGFloat
let verticalMargin: CGFloat
let objectSize: CGSize
public init(columns: Int, width: CGFloat, verticalMargin: CGFloat, objectSize: CGSize) {
self.columns = columns
self.width = width
self.verticalMargin = verticalMargin
self.objectSize = objectSize
}
}
}
public extension SKNode {
public func removeNodeFromCollection(_ withRefresh: Bool = true) {
if let collection = self.parent as? TWCollectionNode {
collection.remove(node: self, reload: withRefresh)
} else {
let message = "TWSKUtils ERROR: Node is not in a TWCollectionNode"
assertionFailure(message)
}
}
}
| mit | 481d85151b566b3a2e0ccb74200711f9 | 31.968421 | 119 | 0.590677 | 4.53913 | false | false | false | false |
rokuz/omim | iphone/Maps/Classes/CustomAlert/CreateBookmarkCategory/BCCreateCategoryAlert.swift | 1 | 4313 | @objc(MWMBCCreateCategoryAlert)
final class BCCreateCategoryAlert: MWMAlert {
private enum State {
case valid
case tooFewSymbols
case tooManySymbols
case nameAlreadyExists
}
@IBOutlet private(set) weak var textField: UITextField!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var textFieldContainer: UIView!
@IBOutlet private weak var centerHorizontaly: NSLayoutConstraint!
@IBOutlet private weak var errorLabel: UILabel!
@IBOutlet private weak var charactersCountLabel: UILabel!
@IBOutlet private weak var rightButton: UIButton! {
didSet {
rightButton.setTitleColor(UIColor.blackHintText(), for: .disabled)
}
}
private var maxCharactersNum: UInt?
private var minCharactersNum: UInt?
private var callback: MWMCheckStringBlock?
@objc static func alert(maxCharachersNum: UInt,
minCharactersNum: UInt,
callback: @escaping MWMCheckStringBlock) -> BCCreateCategoryAlert? {
guard let alert = Bundle.main.loadNibNamed(className(), owner: nil, options: nil)?.first
as? BCCreateCategoryAlert else {
assertionFailure()
return nil
}
alert.titleLabel.text = L("bookmarks_create_new_group")
let text = L("create").capitalized
for s in [.normal, .highlighted, .disabled] as [UIControl.State] {
alert.rightButton.setTitle(text, for: s)
}
alert.maxCharactersNum = maxCharachersNum
alert.minCharactersNum = minCharactersNum
alert.callback = callback
alert.process(state: .tooFewSymbols)
alert.formatCharactersCountText()
MWMKeyboard.add(alert)
return alert
}
@IBAction private func leftButtonTap() {
MWMKeyboard.remove(self)
close(nil)
}
@IBAction private func rightButtonTap() {
guard let callback = callback, let text = textField.text else {
assertionFailure()
return
}
if callback(text) {
MWMKeyboard.remove(self)
close(nil)
} else {
process(state: .nameAlreadyExists)
}
}
@IBAction private func editingChanged(sender: UITextField) {
formatCharactersCountText()
process(state: checkState())
}
private func checkState() -> State {
let count = textField.text!.count
if count <= minCharactersNum! {
return .tooFewSymbols
}
if count > maxCharactersNum! {
return .tooManySymbols
}
return .valid
}
private func process(state: State) {
let color: UIColor
switch state {
case .valid:
color = UIColor.blackHintText()
rightButton.isEnabled = true
errorLabel.isHidden = true
case .tooFewSymbols:
color = UIColor.blackHintText()
errorLabel.isHidden = true
rightButton.isEnabled = false
case .tooManySymbols:
color = UIColor.buttonRed()
errorLabel.isHidden = false
errorLabel.text = L("bookmarks_error_title_list_name_too_long")
rightButton.isEnabled = false
case .nameAlreadyExists:
color = UIColor.buttonRed()
errorLabel.isHidden = false
errorLabel.text = L("bookmarks_error_title_list_name_already_taken")
rightButton.isEnabled = false
}
charactersCountLabel.textColor = color
textFieldContainer.layer.borderColor = color.cgColor
}
private func formatCharactersCountText() {
let count = textField.text!.count
charactersCountLabel.text = String(count) + " / " + String(maxCharactersNum!)
}
}
extension BCCreateCategoryAlert: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if checkState() == .valid {
rightButtonTap()
}
return true
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let str = textField.text as NSString?
let newStr = str?.replacingCharacters(in: range, with: string)
guard let count = newStr?.count else {
return true
}
if count > maxCharactersNum! + 1 {
return false
}
return true
}
}
extension BCCreateCategoryAlert: MWMKeyboardObserver {
func onKeyboardAnimation() {
centerHorizontaly.constant = -MWMKeyboard.keyboardHeight() / 2
layoutIfNeeded()
}
func onKeyboardWillAnimate() {
setNeedsLayout()
}
}
| apache-2.0 | 86e738ef968ca807a1ddcd3a07f31d05 | 26.825806 | 92 | 0.684442 | 4.530462 | false | false | false | false |
rokuz/omim | iphone/Maps/Core/Subscriptions/SubscriptionManager.swift | 1 | 8290 | @objc protocol ISubscriptionManager: class{
typealias SuscriptionsCompletion = ([ISubscription]?, Error?) -> Void
typealias ValidationCompletion = (MWMValidationResult) -> Void
@objc static func canMakePayments() -> Bool
@objc func getAvailableSubscriptions(_ completion: @escaping SuscriptionsCompletion)
@objc func subscribe(to subscription: ISubscription)
@objc func addListener(_ listener: SubscriptionManagerListener)
@objc func removeListener(_ listener: SubscriptionManagerListener)
@objc func validate(completion: ValidationCompletion?)
@objc func restore(_ callback: @escaping ValidationCompletion)
}
@objc protocol SubscriptionManagerListener: AnyObject {
func didFailToSubscribe(_ subscription: ISubscription, error: Error?)
func didSubscribe(_ subscription: ISubscription)
func didDefer(_ subscription: ISubscription)
func didFailToValidate()
func didValidate(_ isValid: Bool)
}
class SubscriptionManager: NSObject, ISubscriptionManager {
private let paymentQueue = SKPaymentQueue.default()
private var productsRequest: SKProductsRequest?
private var subscriptionsComplection: SuscriptionsCompletion?
private var products: [String: SKProduct]?
private var pendingSubscription: ISubscription?
private var listeners = NSHashTable<SubscriptionManagerListener>.weakObjects()
private var restorationCallback: ValidationCompletion?
private var productIds: [String] = []
private var serverId: String = ""
private var vendorId: String = ""
private var purchaseManager: MWMPurchaseManager?
convenience init(productIds: [String], serverId: String, vendorId: String) {
self.init()
self.productIds = productIds
self.serverId = serverId
self.vendorId = vendorId
self.purchaseManager = MWMPurchaseManager(vendorId: vendorId)
}
override private init() {
super.init()
paymentQueue.add(self)
}
deinit {
paymentQueue.remove(self)
}
@objc static func canMakePayments() -> Bool {
return SKPaymentQueue.canMakePayments()
}
@objc func getAvailableSubscriptions(_ completion: @escaping SuscriptionsCompletion){
subscriptionsComplection = completion
productsRequest = SKProductsRequest(productIdentifiers: Set(productIds))
productsRequest!.delegate = self
productsRequest!.start()
}
@objc func subscribe(to subscription: ISubscription) {
pendingSubscription = subscription
guard let product = products?[subscription.productId] else { return }
paymentQueue.add(SKPayment(product: product))
}
@objc func addListener(_ listener: SubscriptionManagerListener) {
listeners.add(listener)
}
@objc func removeListener(_ listener: SubscriptionManagerListener) {
listeners.remove(listener)
}
@objc func validate(completion: ValidationCompletion? = nil) {
validate(false, completion: completion)
}
@objc func restore(_ callback: @escaping ValidationCompletion) {
validate(true) {
callback($0)
}
}
private func validate(_ refreshReceipt: Bool, completion: ValidationCompletion? = nil) {
purchaseManager?.validateReceipt(serverId, refreshReceipt: refreshReceipt) { [weak self] (_, validationResult) in
self?.logEvents(validationResult)
if validationResult == .valid || validationResult == .notValid {
self?.listeners.allObjects.forEach { $0.didValidate(validationResult == .valid) }
self?.paymentQueue.transactions
.filter { self?.productIds.contains($0.payment.productIdentifier) ?? false &&
($0.transactionState == .purchased || $0.transactionState == .restored) }
.forEach { self?.paymentQueue.finishTransaction($0) }
} else {
self?.listeners.allObjects.forEach { $0.didFailToValidate() }
}
completion?(validationResult)
}
}
private func logEvents(_ validationResult: MWMValidationResult) {
switch validationResult {
case .valid:
Statistics.logEvent(kStatInappValidationSuccess, withParameters: [kStatPurchase : serverId])
Statistics.logEvent(kStatInappProductDelivered,
withParameters: [kStatVendor : vendorId, kStatPurchase : serverId], with: .realtime)
case .notValid:
Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 0, kStatPurchase : serverId])
case .serverError:
Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 2, kStatPurchase : serverId])
case .authError:
Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 1, kStatPurchase : serverId])
}
}
}
extension SubscriptionManager: SKProductsRequestDelegate {
func request(_ request: SKRequest, didFailWithError error: Error) {
Statistics.logEvent(kStatInappPaymentError,
withParameters: [kStatError : error.localizedDescription, kStatPurchase : serverId])
DispatchQueue.main.async { [weak self] in
self?.subscriptionsComplection?(nil, error)
self?.subscriptionsComplection = nil
self?.productsRequest = nil
}
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
guard response.products.count == productIds.count else {
DispatchQueue.main.async { [weak self] in
self?.subscriptionsComplection?(nil, NSError(domain: "mapsme.subscriptions", code: -1, userInfo: nil))
self?.subscriptionsComplection = nil
self?.productsRequest = nil
}
return
}
let subscriptions = response.products.map { Subscription($0) }
.sorted { $0.period.rawValue < $1.period.rawValue }
DispatchQueue.main.async { [weak self] in
self?.products = Dictionary(uniqueKeysWithValues: response.products.map { ($0.productIdentifier, $0) })
self?.subscriptionsComplection?(subscriptions, nil)
self?.subscriptionsComplection = nil
self?.productsRequest = nil
}
}
}
extension SubscriptionManager: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
let subscriptionTransactions = transactions.filter {
productIds.contains($0.payment.productIdentifier)
}
subscriptionTransactions
.filter { $0.transactionState == .failed }
.forEach { processFailed($0, error: $0.error) }
if subscriptionTransactions.contains(where: {
$0.transactionState == .purchased || $0.transactionState == .restored
}) {
subscriptionTransactions
.filter { $0.transactionState == .purchased }
.forEach { processPurchased($0) }
subscriptionTransactions
.filter { $0.transactionState == .restored }
.forEach { processRestored($0) }
validate(false)
}
subscriptionTransactions
.filter { $0.transactionState == .deferred }
.forEach { processDeferred($0) }
}
private func processDeferred(_ transaction: SKPaymentTransaction) {
if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId {
listeners.allObjects.forEach { $0.didDefer(ps) }
}
}
private func processPurchased(_ transaction: SKPaymentTransaction) {
paymentQueue.finishTransaction(transaction)
if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId {
Statistics.logEvent(kStatInappPaymentSuccess, withParameters: [kStatPurchase : serverId])
listeners.allObjects.forEach { $0.didSubscribe(ps) }
}
}
private func processRestored(_ transaction: SKPaymentTransaction) {
paymentQueue.finishTransaction(transaction)
if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId {
listeners.allObjects.forEach { $0.didSubscribe(ps) }
}
}
private func processFailed(_ transaction: SKPaymentTransaction, error: Error?) {
paymentQueue.finishTransaction(transaction)
if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId {
let errorText = error?.localizedDescription ?? ""
Statistics.logEvent(kStatInappPaymentError,
withParameters: [kStatPurchase : serverId, kStatError : errorText])
listeners.allObjects.forEach { $0.didFailToSubscribe(ps, error: error) }
}
}
}
| apache-2.0 | a908dc4359282a160bd593c465dd829c | 39.048309 | 117 | 0.72497 | 5.117284 | false | false | false | false |
soxjke/Redux-ReactiveSwift | Example/Simple-Weather-App/Simple-Weather-App/Services/WeatherService.swift | 1 | 7143 | //
// WeatherService.swift
// Simple-Weather-App
//
// Created by Petro Korienev on 10/30/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import Foundation
import Alamofire
import ReactiveSwift
import ObjectMapper
class WeatherService {
private struct Constants {
static let apiKey = "7yLb1UKneALEl7pON1ryH4qAtkCz1eGG"
}
static let shared: WeatherService = WeatherService()
fileprivate lazy var sessionManager: SessionManager = self.setupSessionManager()
fileprivate let appStore: AppStore = AppStore.shared
private init() {
setupObserving()
}
private func setupObserving() {
let locationProducer = self.appStore.producer
.map { $0.location.locationRequestState }
.filter { $0.isSuccess }
.skipRepeats()
.observe(on: QueueScheduler.main)
locationProducer.startWithValues { [weak self] _ in self?.appStore.consume(event: .geopositionRequest )}
let geopositionProducer = self.appStore.producer
.map { $0.weather.geopositionRequestState }
.skipRepeats() // To use skipRepeats we have to implement equatable for GeopositionRequestState
.observe(on: QueueScheduler.main)
geopositionProducer
.filter { $0 == .updating }
.startWithValues { [weak self] _ in self?.performGeopositionRequest() }
geopositionProducer
.filter { $0.isSuccess }
.startWithValues { [weak self] _ in self?.appStore.consume(event: .weatherRequest )}
let weatherProducer = self.appStore.producer
.map { $0.weather.weatherRequestState }
.skipRepeats() // To use skipRepeats we have to implement equatable for WeatherRequestState
.filter { $0 == .updating }
.observe(on: QueueScheduler.main)
weatherProducer.startWithValues { [weak self] _ in self?.performWeatherRequest() }
}
private func setupSessionManager() -> SessionManager {
return SessionManager.default // let's use very default for simplicity
}
}
extension WeatherService {
fileprivate func performGeopositionRequest() {
guard case .success(let latitude, let longitude, _) = self.appStore.value.location.locationRequestState else {
// There should be assertion thrown here, but for safety let's error the request
self.appStore.consume(event: .geopositionResult(geoposition: nil, error: AppError.inconsistentStateGeoposition))
return
}
sessionManager
.request(
"https://dataservice.accuweather.com/locations/v1/cities/geoposition/search",
method: .get,
parameters: ["q": "\(latitude),\(longitude)", "apikey": Constants.apiKey])
.responseJSON { [weak self] (dataResponse) in
switch (dataResponse.result) {
case .failure(let error): self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: error))
case .success(let value):
guard let json = value as? [String: Any] else {
self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: AppError.inconsistentAlamofireBehaviour))
return
}
do {
let geoposition = try Geoposition(JSON: json)
self?.appStore.consume(event: .geopositionResult(geoposition: geoposition, error: nil))
} catch (let error) {
self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: error))
}
}
}
}
fileprivate func performWeatherRequest() {
guard case .success(let geoposition) = self.appStore.value.weather.geopositionRequestState else {
// There should be assertion thrown here, but for safety let's error the request
self.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: AppError.inconsistentStateWeather))
return
}
performCurrentConditionsRequest(for: geoposition.key)
}
private func performCurrentConditionsRequest(for key: String) {
sessionManager
.request(
"https://dataservice.accuweather.com/currentconditions/v1/\(key)",
method: .get,
parameters: ["details": "true", "apikey": Constants.apiKey])
.responseJSON { [weak self] (dataResponse) in
switch (dataResponse.result) {
case .failure(let error): self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error))
case .success(let value):
guard let responseJson = value as? [[String: Any]],
let weatherJson = responseJson.first else {
self?.appStore.consume(event: .weatherResult(current: nil, forecast:nil, error: AppError.inconsistentAlamofireBehaviour))
return
}
do {
let weather = try CurrentWeather(JSON: weatherJson)
self?.performForecastRequest(for: key, currentConditions: weather)
} catch (let error) {
self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error))
}
}
}
}
private func performForecastRequest(for key: String, currentConditions: CurrentWeather) {
sessionManager
.request(
"https://dataservice.accuweather.com/forecasts/v1/daily/5day/\(key)",
method: .get,
parameters: ["details": "true", "apikey": Constants.apiKey])
.responseJSON { [weak self] (dataResponse) in
switch (dataResponse.result) {
case .failure(let error): self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error))
case .success(let value):
guard let rootJson = value as? [String: Any],
let forecastsJson = rootJson["DailyForecasts"] as? [[String:Any]] else {
self?.appStore.consume(event: .weatherResult(current: nil, forecast:nil, error: AppError.inconsistentAlamofireBehaviour))
return
}
do {
let forecasts = try Mapper<Weather>().mapArray(JSONArray: forecastsJson)
self?.appStore.consume(event: .weatherResult(current: currentConditions,
forecast: forecasts,
error: nil))
} catch (let error) {
self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error))
}
}
}
}
}
| mit | 1a8c7609a41f3c0b8835d79e600c26a0 | 47.917808 | 145 | 0.58177 | 5.097787 | false | false | false | false |
whipsterCZ/WeatherTest | WeatherTest/Classes/Models/Forecast.swift | 1 | 878 | //
// Forecast.swift
// WeatherTest
//
// Created by Daniel Kouba on 20/02/15.
// Copyright (c) 2015 Daniel Kouba. All rights reserved.
//
import Foundation
class Forecast : NSObject {
var tempreatureC = WEATHER_NA
var tempreatureF = WEATHER_NA
var iconImage = UIImage()
var iconCode : Int {
set(code) {
iconImage = UIImage(named: DI.context.weatherService.iconNameByCode(code))!
}
get {
return 0
}
}
var type = "Now available"
var date = NSDate()
var weekday = WEATHER_NA
func tempreature(short:Bool) -> String
{
if ( DI.context.settings.tempreatureUnit == .Celsius ) {
return tempreatureC + ( short ? "°" :"°C" )
} else {
return tempreatureF + ( short ? "°" :"°F" )
}
}
} | apache-2.0 | e33d3d66fc4ff979b938953901f2cd33 | 19.833333 | 87 | 0.532037 | 3.990868 | false | false | false | false |
emvakar/EKBlurAlert | Sources/EKBlurAlert/EKBlurAlert.swift | 1 | 6971 | //
// EKBlurAlert.swift
// EKBlurAlert
//
// Created by Emil Karimov on 13/08/2020.
// Copyright © 2020 Emil Karimov. All rights reserved.
//
import UIKit
import SnapKit
public enum EKShowType {
case noTexts
case withTitle
case withSubtitle
}
public class EKBlurAlertView: UIView {
private var alertImage: UIImageView!
private var titleLabel: UILabel!
private var subtitleLabel: UILabel!
private var blurView: UIVisualEffectView!
private var contentView: UIView = UIView()
private var viewCornerRadius: CGFloat = 8
private var timer: Timer?
private var autoFade: Bool = true
private var timeAfter: Double = 0.7
public init(
frame: CGRect, titleFont: UIFont = UIFont.systemFont(ofSize: 17, weight: .regular),
subTitleFont: UIFont = UIFont.systemFont(ofSize: 14, weight: .regular),
image: UIImage = UIImage(),
title: String? = nil,
subtitle: String? = nil,
autoFade: Bool = true,
after: Double = 0.7,
radius: CGFloat = 8,
blurEffect: UIBlurEffect.Style = .dark) {
super.init(frame: frame)
createUI(with: image, blurEffect: blurEffect)
setup(title: title, subtitle: subtitle, autoFade: autoFade, after: after, radius: radius, titleFont: titleFont, subTitleFont: subTitleFont)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createUI(with: UIImage(), blurEffect: UIBlurEffect.Style.dark)
}
public override func layoutSubviews() {
layoutIfNeeded()
cornerRadius(viewCornerRadius)
}
public override func didMoveToSuperview() {
contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.15, animations: {
self.contentView.alpha = 1.0
self.contentView.transform = CGAffineTransform.identity
}) { _ in
if self.autoFade {
self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.timeAfter), target: self, selector: #selector(self.removeSelf), userInfo: nil, repeats: false)
} else {
self.removeSelf()
}
}
}
public func setup(title: String? = nil,
subtitle: String? = nil,
autoFade: Bool = true,
after: Double = 3.0,
radius: CGFloat = 8,
titleFont: UIFont = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.regular),
subTitleFont: UIFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)) {
viewCornerRadius = radius
titleLabel.text = title
titleLabel.font = titleFont
subtitleLabel.text = subtitle
subtitleLabel.font = subTitleFont
self.autoFade = autoFade
timeAfter = after
setupConstraints()
}
}
// MARK: - Private
extension EKBlurAlertView {
@objc
private func removeSelf() {
UIView.animate(withDuration: 0.15, animations: {
self.contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.contentView.alpha = 0.0
}) { _ in
self.removeFromSuperview()
}
}
private func cornerRadius(_ radius: CGFloat = 0.0) {
contentView.layer.cornerRadius = radius
contentView.layer.masksToBounds = contentView.layer.cornerRadius > 0
contentView.clipsToBounds = contentView.layer.cornerRadius > 0
}
private func setupContetViewContraints(type: EKShowType) {
contentView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalTo(frame.width / 2)
// switch type {
// case .noTexts:
// make.height.equalTo(self.frame.width / 2)
// case .withTitle:
// make.height.equalTo((self.frame.width / 3) * 2)
// case .withSubtitle:
// make.height.equalTo((self.frame.width / 5) * 3)
// }
}
blurView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
private func setupConstraints() {
contentView.center = center
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.translatesAutoresizingMaskIntoConstraints = true
addSubview(contentView)
if titleLabel.text != nil {
alertImage.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(30)
make.left.equalToSuperview().offset(30)
make.right.equalToSuperview().offset(-30)
make.height.equalTo(contentView.snp.width).offset(-60)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(alertImage.snp.bottom).offset(15)
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
make.height.greaterThanOrEqualTo(21)
}
if subtitleLabel.text != nil {
setupContetViewContraints(type: EKShowType.withSubtitle)
subtitleLabel.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
make.height.greaterThanOrEqualTo(21)
make.bottom.equalToSuperview().offset(-15)
}
} else {
setupContetViewContraints(type: EKShowType.withTitle)
}
} else {
setupContetViewContraints(type: EKShowType.noTexts)
alertImage.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(30)
make.left.equalToSuperview().offset(30)
make.right.equalToSuperview().offset(-30)
make.bottom.equalToSuperview().offset(-30)
make.width.equalTo(contentView.snp.width).offset(-60)
make.height.equalTo(contentView.snp.width).offset(-60)
}
}
}
private func createUI(with image: UIImage, blurEffect: UIBlurEffect.Style = .dark) {
alertImage = UIImageView(image: image)
titleLabel = UILabel()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.lightText
subtitleLabel = UILabel()
subtitleLabel.numberOfLines = 0
subtitleLabel.textAlignment = .center
subtitleLabel.textColor = UIColor.lightText
blurView = UIVisualEffectView(effect: UIBlurEffect(style: blurEffect))
contentView.alpha = 0.0
contentView.addSubview(blurView)
contentView.addSubview(alertImage)
contentView.addSubview(titleLabel)
contentView.addSubview(subtitleLabel)
}
}
| mit | 350dc699588e0553d2c50ba2eb2528cf | 30.538462 | 176 | 0.609469 | 4.757679 | false | false | false | false |
mamouneyya/Fusuma | Sources/FSVideoCameraView.swift | 3 | 12489 | //
// FSVideoCameraView.swift
// Fusuma
//
// Created by Brendan Kirchner on 3/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import AVFoundation
@objc protocol FSVideoCameraViewDelegate: class {
func videoFinished(withFileURL fileURL: URL)
}
final class FSVideoCameraView: UIView {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
weak var delegate: FSVideoCameraViewDelegate? = nil
var session: AVCaptureSession?
var device: AVCaptureDevice?
var videoInput: AVCaptureDeviceInput?
var videoOutput: AVCaptureMovieFileOutput?
var focusView: UIView?
var flashOffImage: UIImage?
var flashOnImage: UIImage?
var videoStartImage: UIImage?
var videoStopImage: UIImage?
fileprivate var isRecording = false
static func instance() -> FSVideoCameraView {
return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView
}
func initialize() {
if session != nil {
return
}
self.backgroundColor = fusumaBackgroundColor
self.isHidden = false
// AVCapture
session = AVCaptureSession()
for device in AVCaptureDevice.devices() {
if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back {
self.device = device
}
}
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
videoOutput = AVCaptureMovieFileOutput()
let totalSeconds = 60.0 //Total Seconds of capture time
let timeScale: Int32 = 30 //FPS
let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale)
videoOutput?.maxRecordedDuration = maxDuration
videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:)))
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil)
videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil)
videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
shotButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
shotButton.setImage(videoStartImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
shotButton.setImage(videoStartImage, for: UIControlState())
}
flashConfiguration()
self.startCamera()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
}
}
func stopCamera() {
if self.isRecording {
self.toggleRecording()
}
session?.stopRunning()
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
self.toggleRecording()
}
fileprivate func toggleRecording() {
guard let videoOutput = videoOutput else {
return
}
self.isRecording = !self.isRecording
let shotImage: UIImage?
if self.isRecording {
shotImage = videoStopImage
} else {
shotImage = videoStartImage
}
self.shotButton.setImage(shotImage, for: UIControlState())
if self.isRecording {
let outputPath = "\(NSTemporaryDirectory())output.mov"
let outputURL = URL(fileURLWithPath: outputPath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: outputPath) {
do {
try fileManager.removeItem(atPath: outputPath)
} catch {
print("error removing item at path: \(outputPath)")
self.isRecording = false
return
}
}
self.flipButton.isEnabled = false
self.flashButton.isEnabled = false
videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self)
} else {
videoOutput.stopRecording()
self.flipButton.isEnabled = true
self.flashButton.isEnabled = true
}
return
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
session?.stopRunning()
do {
session?.beginConfiguration()
if let session = session {
for input in session.inputs {
session.removeInput(input as! AVCaptureInput)
}
let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let device = device as? AVCaptureDevice , device.position == position {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
}
}
}
session?.commitConfiguration()
} catch {
}
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
do {
if let device = device {
try device.lockForConfiguration()
let mode = device.flashMode
if mode == AVCaptureFlashMode.off {
device.flashMode = AVCaptureFlashMode.on
flashButton.setImage(flashOnImage, for: UIControlState())
} else if mode == AVCaptureFlashMode.on {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate {
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("started recording to: \(fileURL)")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("finished recording to: \(outputFileURL)")
self.delegate?.videoFinished(withFileURL: outputFileURL)
}
}
extension FSVideoCameraView {
func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true {
device?.focusMode = AVCaptureFocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = UIColor.white.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
try device.lockForConfiguration()
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
device.unlockForConfiguration()
}
} catch _ {
return
}
}
}
| mit | a134d0bac843cc0093aa5cd1f881da98 | 33.213699 | 163 | 0.558536 | 6.36818 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/ZMOTRMessage+Unarchive.swift | 1 | 2200 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
extension ZMConversation {
fileprivate func unarchive(with message: ZMOTRMessage) {
self.internalIsArchived = false
if self.lastServerTimeStamp != nil, let serverTimestamp = message.serverTimestamp {
self.updateArchived(serverTimestamp, synchronize: false)
}
}
}
extension ZMOTRMessage {
@objc(unarchiveIfNeeded:)
func unarchiveIfNeeded(_ conversation: ZMConversation) {
if let clearedTimestamp = conversation.clearedTimeStamp,
let serverTimestamp = self.serverTimestamp,
serverTimestamp.compare(clearedTimestamp) == ComparisonResult.orderedAscending {
return
}
unarchiveIfCurrentUserIsMentionedOrQuoted(conversation)
unarchiveIfNotSilenced(conversation)
}
private func unarchiveIfCurrentUserIsMentionedOrQuoted(_ conversation: ZMConversation) {
if conversation.isArchived,
let sender = self.sender,
!sender.isSelfUser,
let textMessageData = self.textMessageData,
!conversation.mutedMessageTypes.contains(.mentionsAndReplies),
textMessageData.isMentioningSelf || textMessageData.isQuotingSelf {
conversation.unarchive(with: self)
}
}
private func unarchiveIfNotSilenced(_ conversation: ZMConversation) {
if conversation.isArchived, conversation.mutedMessageTypes == .none {
conversation.unarchive(with: self)
}
}
}
| gpl-3.0 | 979d622f0c18d5c53d1e34072ec39442 | 33.920635 | 92 | 0.703182 | 5.022831 | false | false | false | false |
LKY769215561/KYHandMade | KYHandMade/KYHandMade/Class/Home(首页)/Model/KYSlideModel.swift | 1 | 1258 | //
// KYSlide.swift
// KYHandMade
//
// Created by Kerain on 2017/6/13.
// Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved.
// 轮播图
import UIKit
class KYSlideModel: NSObject {
/*
"hand_daren" = 0;
"hand_id" = "http://www.shougongke.com/index.php?m=Topic&a=topicDetail&topic_id=1593&topic_type=shiji&funding_id=44";
"host_pic" = "http://imgs.shougongker.com/Public/data/lunbo/1497334789_y45a8kkesy.jpg@!home_page";
itemtype = "topic_detail_h5";
"step_count" = "";
subject = "\U4f17\U7b79\Uff5c\U62fe\U827a\U5b66\U5802\U5468\U5e74\U5e86\Uff0c\U5168\U7f51\U6700\U4f4e\U4ef7\U9080\U4f60\U505a\U624b\U5de5";
template = 4;
type = 2;
"user_name" = "\U624b\U5de5\U5ba2\U5b98\U65b9";
*/
var hand_daren : String?
var hand_id : String?
var host_pic : String?
var itemtype : String?
var step_count : String?
var subject : String?
var template : String?
var type : String?
var user_name : String?
// var is_expired : String?
init(dict:[String : AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| apache-2.0 | dae6f5e1e9ccdc0d27a5cb1250e5b9ae | 26.795455 | 144 | 0.621423 | 2.670306 | false | false | false | false |
puyanLiu/LPYFramework | 第三方框架改造/pull-to-refresh-master/ESPullToRefreshExample/ESPullToRefreshExample/Custom/Meituan/UIView+Extension.swift | 1 | 2980 | //
// UIView+Extension.swift
// QQMProjectSwift
//
// Created by liupuyan on 2017/5/12.
// Copyright © 2017年 liupuyan. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
/**
* 高度
*/
var height_: CGFloat {
get {
return frame.size.height
}
set(newValue) {
var frame: CGRect = self.frame
frame.size.height = newValue
self.frame = frame
}
}
/**
* 宽度
*/
var width_: CGFloat {
get {
return frame.size.width
}
set(newValue) {
var frame: CGRect = self.frame
frame.size.width = newValue
self.frame = frame
}
}
var x_: CGFloat {
get {
return frame.origin.x
}
set(newValue) {
var frame: CGRect = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
var y_: CGFloat {
get {
return frame.origin.y
}
set(newValue) {
var frame: CGRect = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
var centerX_: CGFloat {
get {
return center.x
}
set(newValue) {
var center: CGPoint = self.center
center.x = newValue
self.center = center
}
}
var centerY_: CGFloat {
get {
return center.y
}
set(newValue) {
var center: CGPoint = self.center
center.y = newValue
self.center = center
}
}
var size_: CGSize {
get {
return frame.size
}
set(newValue) {
var frame: CGRect = self.frame
frame.size = newValue
self.frame = frame
}
}
}
// MARK: - layer
extension UIView {
class func createGradientLayer(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientAngle: CGFloat) -> CAGradientLayer {
return createGradientLayer(frame: frame, startColor: startColor, endColor: endColor, gradientAngle: gradientAngle, startPoint: CGPoint(x: 1, y: 1), endPoint: CGPoint(x: 0, y: tan(gradientAngle)))
}
class func createGradientLayer(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientAngle: CGFloat, startPoint: CGPoint, endPoint: CGPoint) -> CAGradientLayer {
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.frame = frame
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
if gradientAngle > 0 {
let l: NSNumber = NSNumber(value: Float(tan(gradientAngle)))
gradientLayer.locations = [l]
}
let startColor = startColor.cgColor
let endColor = endColor.cgColor
gradientLayer.colors = [startColor, endColor]
return gradientLayer
}
}
| apache-2.0 | 2459d00ef77409ae87e15d7b04bacf38 | 25.508929 | 203 | 0.542607 | 4.639063 | false | false | false | false |
Mozharovsky/XMLParser | XMLParser Demo/XMLParser Demo/AppDelegate.swift | 4 | 1500 | //
// AppDelegate.swift
// XMLParser Demo
//
// Created by Eugene Mozharovsky on 8/29/15.
// Copyright © 2015 DotMyWay LCC. All rights reserved.
//
import UIKit
import XMLParser
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
/// Parsing an XML string from a Dictionary
let body = [
"request" : [
"meta" : [
"type" : "getOrder",
"date" : "2015-08-29 12:00:00",
"device_name" : "iPhone 6 Plus",
"device_os_version" : "iOS 9"
]
],
"encryption" : [
"type" : "RSA"
]
]
let header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
let result = XMLParser.sharedParser.encode(body, header: header)
print(result)
/// Extracting data from an XML converted string
let convertedString = "<request><meta><type>getOrder</type><date>2015-08-29 12:00:00</date><device_name>iPhone 6 Plus</device_name><device_os_version>iOS 9</device_os_version></meta></request><encryption><type>RSA</type></encryption>"
let result1 = XMLParser.sharedParser.decode(convertedString)
print(result1)
return true
}
}
| mit | 8befb2fe6baf3fd74b6deed3b638197c | 28.392157 | 242 | 0.556371 | 4.370262 | false | false | false | false |
karwa/swift | test/Constraints/closures.swift | 1 | 31827 | // RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Closures with inout arguments and '__shared' conversions.
func inoutToSharedConversions() {
func fooOW<T, U>(_ f : (__owned T) -> U) {}
fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed
fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed
fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned Int) -> Int'}}
func fooIO<T, U>(_ f : (inout T) -> U) {}
fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed
fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(inout Int) -> Int'}}
fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout Int) -> Int'}}
fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout Int) -> Int'}}
func fooSH<T, U>(_ f : (__shared T) -> U) {}
fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed
fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared Int) -> Int'}}
fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed
}
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{add () to forward @autoclosure parameter}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall // expected-error {{cannot call value of non-function type 'Bool'}}
{
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}}
{ consume($0) }(42)
;
({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}}
{ consume($0) }(42)
;
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}}
{ [n] in consume($0) }(42)
;
({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}}
{ [n] in consume($0) }(42)
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42)
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42)
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{cannot convert value of type 'Int' to expected element type 'Double'}}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '(@escaping (_, _) -> _)'}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
func verify_NotAC_to_AC_failure(_ arg: () -> ()) {
func takesAC(_ arg: @autoclosure () -> ()) {}
takesAC(arg) // expected-error {{add () to forward @autoclosure parameter}} {{14-14=()}}
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
// expected-note@-1 {{where 'Key' = 'Object?'}}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+2 {{instance method 'append(value:forKey:)' requires that 'Object?' be a class type}}
// expected-note @+1 {{wrapped type 'Object' satisfies this requirement}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Similar to SR1069 but with multiple generic arguments
func simplified1069() {
class C {}
struct S {
func genericallyNonOptional<T: AnyObject>(_ a: T, _ b: T, _ c: T) { }
// expected-note@-1 {{where 'T' = 'Optional<C>'}}
func f(_ a: C?, _ b: C?, _ c: C) {
genericallyNonOptional(a, b, c) // expected-error {{instance method 'genericallyNonOptional' requires that 'Optional<C>' be a class type}}
// expected-note @-1 {{wrapped type 'C' satisfies this requirement}}
}
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)}) // expected-error@:27 {{argument passed to call that takes no arguments}}
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> <#Result#> }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> <#Result#> in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {} // expected-note {{candidate expects value of type 'String' for parameter #1}}
func f19997471(_ x: Int) {} // expected-note {{candidate expects value of type 'Int' for parameter #1}}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{no exact matches in call to global function 'f19997471'}}
}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> <#Result#> }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) throws -> U' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} {{17-17=UInt8(}} {{25-25=)}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
// expected-error@-1:11 {{cannot call value of non-function type '()'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> <#Result#> }}
print("a")
return "hi"
}
}
// In the example below, SR-2505 started preferring C_SR_2505.test(_:) over
// test(it:). Prior to Swift 5.1, we emulated the old behavior. However,
// that behavior is inconsistent with the typical approach of preferring
// overloads from the concrete type over one from a protocol, so we removed
// the hack.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: the diagnostic about capturing 'self', indicates that we have
// selected test(_) rather than test(it:)
return c.test { o in test(o) } // expected-error{{call to method 'test' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} expected-note{{reference 'self.' explicitly}}
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{value of type 'Int' has no subscripts}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{13-13= _ in}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} // expected-note {{in call to function 'sr3520_set_via_closure'}}
sr3520_set_via_closure({ $0.number1 = $1 })
// expected-error@-1 {{generic parameter 'S' could not be inferred}}
// expected-error@-2 {{generic parameter 'T' could not be inferred}}
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().compactMap { $0 }.compactMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'compactMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].compactMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 }
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
r32432145 { _ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
// rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller
[1, 2].first { $0.foo = 3 }
// expected-error@-1 {{value of type 'Int' has no member 'foo'}}
// expected-error@-2 {{cannot convert value of type '()' to closure result type 'Bool'}}
// rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem
protocol A_SR_5030 {
associatedtype Value
func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U>
}
struct B_SR_5030<T> : A_SR_5030 {
typealias Value = T
func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() }
}
func sr5030_exFalso<T>() -> T {
fatalError()
}
extension A_SR_5030 {
func foo() -> B_SR_5030<Int> {
let tt : B_SR_5030<Int> = sr5030_exFalso()
return tt.map { x in (idx: x) }
// expected-error@-1 {{cannot convert value of type '(idx: Int)' to closure result type 'Int'}}
}
}
// rdar://problem/33296619
let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}}
[1].forEach { _ in
_ = "\(u)"
_ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
class SR5666 {
var property: String?
}
func testSR5666(cs: [SR5666?]) -> [String?] {
return cs.map({ c in
let a = c.propertyWithTypo ?? "default"
// expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}}
let b = "\(a)"
return b
})
}
// Ensure that we still do the appropriate pointer conversion here.
_ = "".withCString { UnsafeMutableRawPointer(mutating: $0) }
// rdar://problem/34077439 - Crash when pre-checking bails out and
// leaves us with unfolded SequenceExprs inside closure body.
_ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}}
return offset ? 0 : 0
}
struct SR5202<T> {
func map<R>(fn: (T) -> R) {}
}
SR5202<()>().map{ return 0 }
SR5202<()>().map{ _ in return 0 }
SR5202<Void>().map{ return 0 }
SR5202<Void>().map{ _ in return 0 }
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// rdar://problem/33429010
struct I_33429010 : IteratorProtocol {
func next() -> Int? {
fatalError()
}
}
extension Sequence {
public func rdar33429010<Result>(into initialResult: Result,
_ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> ()
) rethrows -> Result {
return initialResult
}
}
extension Int {
public mutating func rdar33429010_incr(_ inc: Int) {
self += inc
}
}
func rdar33429010_2() {
let iter = I_33429010()
var acc: Int = 0 // expected-warning {{}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 })
// expected-warning@-1 {{result of operator '+' is unused}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) })
}
class P_33429010 {
var name: String = "foo"
}
class C_33429010 : P_33429010 {
}
func rdar33429010_3() {
let arr = [C_33429010()]
let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok
}
func rdar36054961() {
func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {}
bar(dict: ["abc": { str, range, _ in
str.replaceSubrange(range, with: str[range].reversed())
}])
}
protocol P_37790062 {
associatedtype T
var elt: T { get }
}
func rdar37790062() {
struct S<T> {
init(_ a: () -> T, _ b: () -> T) {}
}
class C1 : P_37790062 {
typealias T = Int
var elt: T { return 42 }
}
class C2 : P_37790062 {
typealias T = (String, Int, Void)
var elt: T { return ("question", 42, ()) }
}
func foo() -> Int { return 42 }
func bar() -> Void {}
func baz() -> (String, Int) { return ("question", 42) }
func bzz<T>(_ a: T) -> T { return a }
func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt }
_ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}}
_ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}}
_ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}}
}
// <rdar://problem/39489003>
typealias KeyedItem<K, T> = (key: K, value: T)
protocol Node {
associatedtype T
associatedtype E
associatedtype K
var item: E {get set}
var children: [(key: K, value: T)] {get set}
}
extension Node {
func getChild(for key:K)->(key: K, value: T) {
return children.first(where: { (item:KeyedItem) -> Bool in
return item.key == key
// expected-error@-1 {{binary operator '==' cannot be applied to two 'Self.K' operands}}
})!
}
}
// Make sure we don't allow this anymore
func takesTwo(_: (Int, Int) -> ()) {}
func takesTwoInOut(_: (Int, inout Int) -> ()) {}
takesTwo { _ in } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
takesTwoInOut { _ in } // expected-error {{contextual closure type '(Int, inout Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
}
// rdar://problem/42337247
func overloaded(_ handler: () -> Int) {} // expected-note {{found this candidate}}
func overloaded(_ handler: () -> Void) {} // expected-note {{found this candidate}}
overloaded { } // empty body => inferred as returning ()
overloaded { print("hi") } // single-expression closure => typechecked with body
overloaded { print("hi"); print("bye") } // multiple expression closure without explicit returns; can default to any return type
// expected-error@-1 {{ambiguous use of 'overloaded'}}
func not_overloaded(_ handler: () -> Int) {}
// expected-note@-1 {{'not_overloaded' declared here}}
not_overloaded { } // empty body
// expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}}
not_overloaded { print("hi") } // single-expression closure
// expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}}
// no error in -typecheck, but dataflow diagnostics will complain about missing return
not_overloaded { print("hi"); print("bye") } // multiple expression closure
func apply(_ fn: (Int) throws -> Int) rethrows -> Int {
return try fn(0)
}
enum E : Error {
case E
}
func test() -> Int? {
return try? apply({ _ in throw E.E })
}
var fn: () -> [Int] = {}
// expected-error@-1 {{cannot convert value of type '()' to closure result type '[Int]'}}
fn = {}
// expected-error@-1 {{cannot assign value of type '() -> ()' to type '() -> [Int]'}}
func test<Instances : Collection>(
_ instances: Instances,
_ fn: (Instances.Index, Instances.Index) -> Bool
) { fatalError() }
test([1]) { _, _ in fatalError(); () }
// rdar://problem/40537960 - Misleading diagnostic when using closure with wrong type
protocol P_40537960 {}
func rdar_40537960() {
struct S {
var v: String
}
struct L : P_40537960 {
init(_: String) {}
}
struct R<T : P_40537960> {
init(_: P_40537960) {}
}
struct A<T: Collection, P: P_40537960> { // expected-note {{'P' declared as parameter to type 'A'}}
typealias Data = T.Element
init(_: T, fn: (Data) -> R<P>) {}
}
var arr: [S] = []
_ = A(arr, fn: { L($0.v) }) // expected-error {{cannot convert value of type 'L' to closure result type 'R<P>'}}
// expected-error@-1 {{generic parameter 'P' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<[S], <#P: P_40537960#>>}}
}
// rdar://problem/45659733
func rdar_45659733() {
func foo<T : BinaryInteger>(_: AnyHashable, _: T) {}
func bar(_ a: Int, _ b: Int) {
_ = (a ..< b).map { i in foo(i, i) } // Ok
}
struct S<V> {
func map<T>(
get: @escaping (V) -> T,
set: @escaping (inout V, T) -> Void
) -> S<T> {
fatalError()
}
subscript<T>(
keyPath: WritableKeyPath<V, T?>,
default defaultValue: T
) -> S<T> {
return map(
get: { $0[keyPath: keyPath] ?? defaultValue },
set: { $0[keyPath: keyPath] = $1 }
) // Ok, make sure that we deduce result to be S<T>
}
}
}
func rdar45771997() {
struct S {
mutating func foo() {}
}
let _: Int = { (s: inout S) in s.foo() }
// expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}}
}
struct rdar30347997 {
func withUnsafeMutableBufferPointer(body : (inout Int) -> ()) {}
func foo() {
withUnsafeMutableBufferPointer { // expected-error {{cannot convert value of type '(Int) -> ()' to expected argument type '(inout Int) -> ()'}}
(b : Int) in
}
}
}
struct rdar43866352<Options> {
func foo() {
let callback: (inout Options) -> Void
callback = { (options: Options) in } // expected-error {{cannot assign value of type '(Options) -> ()' to type '(inout Options) -> Void'}}
}
}
extension Hashable {
var self_: Self {
return self
}
}
do {
struct S<
C : Collection,
I : Hashable,
R : Numeric
> {
init(_ arr: C,
id: KeyPath<C.Element, I>,
content: @escaping (C.Element) -> R) {}
}
func foo(_ arr: [Int]) {
_ = S(arr, id: \.self_) {
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{30-30=_ in }}
return 42
}
}
}
// Don't allow result type of a closure to end up as a noescape type
// The funny error is because we infer the type of badResult as () -> ()
// via the 'T -> U => T -> ()' implicit conversion.
let badResult = { (fn: () -> ()) in fn }
// expected-error@-1 {{expression resolves to an unused function}}
// rdar://problem/55102498 - closure's result type can't be inferred if the last parameter has a default value
func test_trailing_closure_with_defaulted_last() {
func foo<T>(fn: () -> T, value: Int = 0) {}
foo { 42 } // Ok
foo(fn: { 42 }) // Ok
}
| apache-2.0 | 5b88067d40a0771a6b26eb9985416cb8 | 33.669935 | 286 | 0.626041 | 3.358341 | false | false | false | false |
24/ios-o2o-c | gxc/Common/GXTableViewCell.swift | 1 | 6754 | //
// TableViewCell.swift
// gx
//
// Created by gx on 14/11/9.
// Copyright (c) 2014年 gx. All rights reserved.
//
//
// ProgramNoteTableViewCell.swift
// NotesSwift
//
// Created by Samuel Susla on 9/12/14.
// Copyright (c) 2014 Samuel Susla. All rights reserved.
//
import UIKit
protocol GXTableViewCellDelegate {
// func didLongPressCell(cell: GXTableViewCell, recognizer: UILongPressGestureRecognizer)
// func didTapCell(cell: GXTableViewCell, recognizer: UITapGestureRecognizer)
// func didDoubleTapCell(cell: GXTableViewCell, recognizer: UITapGestureRecognizer)
}
class GXTableViewCell: UITableViewCell {
var delegate: GXTableViewCellDelegate?
var titleLabel = UILabel()
var addressLabel = UILabel()
var shopImageView = UIImageView(image: UIImage(named: "ddd"))
var shopInfoView = UIView()
var shopStatueView = UIImageView(image: UIImage(named: "ddd"))
//info
var locationImageView = UIImageView(image: UIImage(named: "shop_location.png"))
var locationLengthLabel = UILabel()
// locationLengthLabel.textColor = UIColor(fromHexString: "#2F9BD4")
// locationLengthLabel.backgroundColor = UIColor(fromHexString: "#F1F1F1")
var carImageView = UIImageView(image: UIImage(named: "shop_car.png"))
var carLabel = UILabel()
var discountImageView = UIImageView(image: UIImage(named: "shop_dazhe.png"))
var discountLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
// self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
titleLabel.font = UIFont (name: "Heiti SC", size: 16)
addressLabel.font = UIFont (name: "Heiti SC", size: 12)
locationLengthLabel.font = UIFont(name: "Heiti SC", size: 10)
carLabel.font = UIFont(name: "Heiti SC", size: 10)
discountLabel.font = UIFont(name: "Heiti SC", size: 10)
contentView.addSubview(titleLabel)
contentView.addSubview(addressLabel)
contentView.addSubview(shopImageView)
contentView.addSubview(shopInfoView)
contentView.addSubview(shopStatueView)
shopInfoView.addSubview(locationImageView)
shopInfoView.addSubview(locationLengthLabel)
shopInfoView.addSubview(carImageView)
shopInfoView.addSubview(carLabel)
shopInfoView.addSubview(discountImageView)
shopInfoView.addSubview(discountLabel)
let padding = 10
shopImageView.snp_makeConstraints { make in
make.centerY.equalTo(self.contentView.snp_centerY)
make.left.equalTo(self.contentView.snp_left).offset(5)
make.width.equalTo(48)
make.height.equalTo(40)
}
titleLabel.snp_makeConstraints { make in
make.top.equalTo(self.contentView.snp_top).offset(8)
make.left.equalTo(self.shopImageView.snp_right).offset(15)
make.width.equalTo(200)
make.height.equalTo(20)
}
addressLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
addressLabel.numberOfLines = 2
addressLabel.snp_makeConstraints { make in
make.top.equalTo(self.titleLabel.snp_bottom)
make.left.equalTo(self.shopImageView.snp_right).offset(15)
make.width.equalTo(200)
make.height.equalTo(30)
}
shopInfoView.snp_makeConstraints { make in
make.bottom.equalTo(self.snp_bottom).offset(-5)
make.left.equalTo(self.shopImageView.snp_right).offset(15)
make.width.equalTo(200)
make.height.equalTo(15)
}
locationImageView.snp_makeConstraints { make in
// make.top.equalTo(self.shopInfoView.snp_top)
make.centerY.equalTo(self.shopInfoView.snp_centerY)
make.left.equalTo(self.shopInfoView.snp_left)
make.width.equalTo(13)
make.height.equalTo(13)
}
locationLengthLabel.snp_makeConstraints { make in
make.centerY.equalTo(self.shopInfoView.snp_centerY)
// make.top.equalTo(self.shopInfoView.snp_top)
make.left.equalTo(self.locationImageView.snp_right)
make.width.equalTo(40)
make.height.equalTo(15)
}
carImageView.snp_makeConstraints { make in
make.centerY.equalTo(self.shopInfoView.snp_centerY)
// make.top.equalTo(self.shopInfoView.snp_top)
make.left.equalTo(self.locationLengthLabel.snp_right)
make.width.equalTo(13)
make.height.equalTo(10)
}
carLabel.snp_makeConstraints { make in
make.centerY.equalTo(self.shopInfoView.snp_centerY)
// make.top.equalTo(self.shopInfoView.snp_top)
make.left.equalTo(self.carImageView.snp_right)
make.width.equalTo(50)
make.height.equalTo(15)
}
discountImageView.snp_makeConstraints { make in
make.centerY.equalTo(self.shopInfoView.snp_centerY)
// make.top.equalTo(self.shopInfoView.snp_top)
make.left.equalTo(self.carLabel.snp_right)
make.width.equalTo(13)
make.height.equalTo(13)
}
discountLabel.snp_makeConstraints { make in
make.centerY.equalTo(self.shopInfoView.snp_centerY)
// make.top.equalTo(self.shopInfoView.snp_top)
make.left.equalTo(self.discountImageView.snp_right)
make.width.equalTo(30)
make.height.equalTo(15)
}
//右边图片
shopStatueView.snp_makeConstraints { make in
make.centerY.equalTo(self.contentView.snp_centerY)
make.right.equalTo(self.contentView.snp_right).offset(-13)
make.width.equalTo(23)
make.height.equalTo(23)
}
}
//MARK: Actions
// internal func didLongPress(recognizer: UILongPressGestureRecognizer){
// delegate?.didLongPressCell(self, recognizer: recognizer)
// }
//
// internal func didTap(recognizer: UITapGestureRecognizer) {
// delegate?.didTapCell(self, recognizer: recognizer)
// }
//
// internal func didDoubleTap(recognizer: UITapGestureRecognizer) {
// delegate?.didDoubleTapCell(self, recognizer: recognizer)
// }
}
| mit | 04368bd227692dcb460951fda51bc9ba | 33.060606 | 92 | 0.632117 | 4.331407 | false | false | false | false |
edwinbosire/A-SwiftProgress | EBProgressView/ViewController.swift | 1 | 1705 | //
// ViewController.swift
// EBProgressView
//
// Created by edwin bosire on 06/11/2015.
// Copyright © 2015 Edwin Bosire. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var progressLabel: UILabel!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refresh")
self.navigationController?.navigationItem.leftBarButtonItem = refresh;
/** To set the progress bar, assuming change is your progress change
var change = 10;
let navigationBar = self.navigationController as! EBNavigationController
if let navgationBarProgress = navigationBar.lineProgressView {
navgationBarProgress.progress = progress + change
}
*/
self.progressLabel.text = "\(0.0) %"
simulateProgress()
}
func refresh () {
NSLog("Refresh the data here")
}
func simulateProgress() {
let delay: Double = 2.0
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
let increment = Double(arc4random() % 5) / Double(10.0) + 0.1
let navigationBar = self.navigationController as! EBNavigationController
let progress = navigationBar.lineProgressView.progress + increment
navigationBar.lineProgressView.progress = progress
self.progressLabel.text = "\(progress*100) %"
if (progress < 1){
self.simulateProgress()
}else {
// Using a callback function here would be ideal
// navigationBar.lineProgressView.stopAnimating()
NSLog("Finished animating progress bar")
}
}
}
}
| mit | a6007c439ea9cf6461ded5df503841d8 | 26.047619 | 95 | 0.711268 | 3.972028 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressKit/WordPressKit/WordPressOrgXMLRPCApi.swift | 1 | 14737 | import Foundation
import wpxmlrpc
open class WordPressOrgXMLRPCApi: NSObject {
public typealias SuccessResponseBlock = (AnyObject, HTTPURLResponse?) -> ()
public typealias FailureReponseBlock = (_ error: NSError, _ httpResponse: HTTPURLResponse?) -> ()
fileprivate let endpoint: URL
fileprivate let userAgent: String?
fileprivate var ongoingProgress = [URLSessionTask: Progress]()
fileprivate lazy var session: Foundation.URLSession = {
let sessionConfiguration = URLSessionConfiguration.default
var additionalHeaders: [String : AnyObject] = ["Accept-Encoding": "gzip, deflate" as AnyObject]
if let userAgent = self.userAgent {
additionalHeaders["User-Agent"] = userAgent as AnyObject?
}
sessionConfiguration.httpAdditionalHeaders = additionalHeaders
let session = Foundation.URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
return session
}()
fileprivate var uploadSession: Foundation.URLSession {
get {
return self.session
}
}
public init(endpoint: URL, userAgent: String? = nil) {
self.endpoint = endpoint
self.userAgent = userAgent
super.init()
}
deinit {
session.finishTasksAndInvalidate()
}
/**
Cancels all ongoing and makes the session so the object will not fullfil any more request
*/
open func invalidateAndCancelTasks() {
session.invalidateAndCancel()
}
// MARK: - Network requests
/**
Check if username and password are valid credentials for the xmlrpc endpoint.
- parameter username: username to check
- parameter password: password to check
- parameter success: callback block to be invoked if credentials are valid, the object returned in the block is the options dictionary for the site.
- parameter failure: callback block to be invoked is credentials fail
*/
open func checkCredentials(_ username: String,
password: String,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) {
let parameters: [AnyObject] = [0 as AnyObject, username as AnyObject, password as AnyObject]
callMethod("wp.getOptions", parameters: parameters, success: success, failure: failure)
}
/**
Executes a XMLRPC call for the method specificied with the arguments provided.
- parameter method: the xmlrpc method to be invoked
- parameter parameters: the parameters to be encoded on the request
- parameter success: callback to be called on successful request
- parameter failure: callback to be called on failed request
- returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method
returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback
will be invoked with the error specificing the serialization issues.
*/
@discardableResult open func callMethod(_ method: String,
parameters: [AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
//Encode request
let request: URLRequest
do {
request = try requestWithMethod(method, parameters: parameters)
} catch let encodingError as NSError {
failure(encodingError, nil)
return nil
}
var progress: Progress?
// Create task
let task = session.dataTask(with: request, completionHandler: { (data, urlResponse, error) in
if let uploadProgress = progress {
uploadProgress.completedUnitCount = uploadProgress.totalUnitCount
}
do {
let responseObject = try self.handleResponseWithData(data, urlResponse: urlResponse, error: error as NSError?)
DispatchQueue.main.async {
success(responseObject, urlResponse as? HTTPURLResponse)
}
} catch let error as NSError {
DispatchQueue.main.async {
failure(error, urlResponse as? HTTPURLResponse)
}
return
}
})
progress = createProgressForTask(task)
task.resume()
return progress
}
/**
Executes a XMLRPC call for the method specificied with the arguments provided, by streaming the request from a file.
This allows to do requests that can use a lot of memory, like media uploads.
- parameter method: the xmlrpc method to be invoked
- parameter parameters: the parameters to be encoded on the request
- parameter success: callback to be called on successful request
- parameter failure: callback to be called on failed request
- returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method
returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback
will be invoked with the error specificing the serialization issues.
*/
@discardableResult open func streamCallMethod(_ method: String,
parameters: [AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
let fileURL = URLForTemporaryFile()
//Encode request
let request: URLRequest
do {
request = try streamingRequestWithMethod(method, parameters: parameters, usingFileURLForCache: fileURL)
} catch let encodingError as NSError {
failure(encodingError, nil)
return nil
}
// Create task
let session = uploadSession
var progress: Progress?
let task = session.uploadTask(with: request, fromFile: fileURL, completionHandler: { (data, urlResponse, error) in
if session != self.session {
session.finishTasksAndInvalidate()
}
let _ = try? FileManager.default.removeItem(at: fileURL)
do {
let responseObject = try self.handleResponseWithData(data, urlResponse: urlResponse, error: error as NSError?)
success(responseObject, urlResponse as? HTTPURLResponse)
} catch let error as NSError {
failure(error, urlResponse as? HTTPURLResponse)
}
if let uploadProgress = progress {
uploadProgress.completedUnitCount = uploadProgress.totalUnitCount
}
})
task.resume()
progress = createProgressForTask(task)
return progress
}
// MARK: - Request Building
fileprivate func requestWithMethod(_ method: String, parameters: [AnyObject]?) throws -> URLRequest {
let mutableRequest = NSMutableURLRequest(url: endpoint)
mutableRequest.httpMethod = "POST"
mutableRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type")
let encoder = WPXMLRPCEncoder(method: method, andParameters: parameters)
mutableRequest.httpBody = try encoder.dataEncoded()
return mutableRequest as URLRequest
}
fileprivate func streamingRequestWithMethod(_ method: String, parameters: [AnyObject]?, usingFileURLForCache fileURL: URL) throws -> URLRequest {
let mutableRequest = NSMutableURLRequest(url: endpoint)
mutableRequest.httpMethod = "POST"
mutableRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type")
let encoder = WPXMLRPCEncoder(method: method, andParameters: parameters)
try encoder.encode(toFile: fileURL.path)
var optionalFileSize: AnyObject?
try (fileURL as NSURL).getResourceValue(&optionalFileSize, forKey: URLResourceKey.fileSizeKey)
if let fileSize = optionalFileSize as? NSNumber {
mutableRequest.setValue(fileSize.stringValue, forHTTPHeaderField: "Content-Length")
}
return mutableRequest as URLRequest
}
fileprivate func URLForTemporaryFile() -> URL {
let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.xmlrpc"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
return fileURL
}
// MARK: - Progress reporting
fileprivate func createProgressForTask(_ task: URLSessionTask) -> Progress {
// Progress report
let progress = Progress(parent: Progress.current(), userInfo: nil)
progress.totalUnitCount = 1
if let contentLengthString = task.originalRequest?.allHTTPHeaderFields?["Content-Length"],
let contentLength = Int64(contentLengthString) {
// Sergio Estevao: Add an extra 1 unit to the progress to take in account the upload response and not only the uploading of data
progress.totalUnitCount = contentLength + 1
}
progress.cancellationHandler = {
task.cancel()
}
ongoingProgress[task] = progress
return progress
}
// MARK: - Handling of data
fileprivate func handleResponseWithData(_ originalData: Data?, urlResponse: URLResponse?, error: NSError?) throws -> AnyObject {
guard let data = originalData,
let httpResponse = urlResponse as? HTTPURLResponse,
let contentType = httpResponse.allHeaderFields["Content-Type"] as? String, error == nil else {
if let unwrappedError = error {
throw convertError(unwrappedError, data: originalData)
} else {
throw convertError(WordPressOrgXMLRPCApiError.unknown as NSError, data: originalData)
}
}
if ["application/xml", "text/xml"].filter({ (type) -> Bool in return contentType.hasPrefix(type)}).count == 0 {
throw convertError(WordPressOrgXMLRPCApiError.responseSerializationFailed as NSError, data: originalData)
}
guard let decoder = WPXMLRPCDecoder(data: data) else {
throw WordPressOrgXMLRPCApiError.responseSerializationFailed
}
guard !(decoder.isFault()), let responseXML = decoder.object() else {
if let decoderError = decoder.error() {
throw convertError(decoderError as NSError, data: data)
} else {
throw WordPressOrgXMLRPCApiError.responseSerializationFailed
}
}
return responseXML as AnyObject
}
open static let WordPressOrgXMLRPCApiErrorKeyData = "WordPressOrgXMLRPCApiErrorKeyData"
open static let WordPressOrgXMLRPCApiErrorKeyDataString = "WordPressOrgXMLRPCApiErrorKeyDataString"
fileprivate func convertError(_ error: NSError, data: Data?) -> NSError {
if let data = data {
var userInfo: [AnyHashable: Any] = error.userInfo
userInfo[type(of: self).WordPressOrgXMLRPCApiErrorKeyData] = data
userInfo[type(of: self).WordPressOrgXMLRPCApiErrorKeyDataString] = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
return NSError(domain: error.domain, code: error.code, userInfo: userInfo)
}
return error
}
}
extension WordPressOrgXMLRPCApi: URLSessionTaskDelegate, URLSessionDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard let progress = ongoingProgress[task] else {
return
}
progress.completedUnitCount = totalBytesSent
if (totalBytesSent == totalBytesExpectedToSend) {
ongoingProgress.removeValue(forKey: task)
}
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
switch challenge.protectionSpace.authenticationMethod {
case NSURLAuthenticationMethodServerTrust:
if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 {
completionHandler(.useCredential, credential)
return
}
var result = SecTrustResultType.invalid
if let serverTrust = challenge.protectionSpace.serverTrust {
let certificateStatus = SecTrustEvaluate(serverTrust, &result)
if certificateStatus == 0 && result == SecTrustResultType.recoverableTrustFailure {
DispatchQueue.main.async(execute: { () in
HTTPAuthenticationAlertController.presentWithChallenge(challenge, handler: completionHandler)
})
} else {
completionHandler(.performDefaultHandling, nil)
}
}
default:
completionHandler(.performDefaultHandling, nil)
}
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
switch challenge.protectionSpace.authenticationMethod {
case NSURLAuthenticationMethodHTTPBasic:
if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 {
completionHandler(.useCredential, credential)
} else {
DispatchQueue.main.async(execute: { () in
HTTPAuthenticationAlertController.presentWithChallenge(challenge, handler: completionHandler)
})
}
default:
completionHandler(.performDefaultHandling, nil)
}
}
}
/**
Error constants for the WordPress XMLRPC API
- RequestSerializationFailed: The serialization of the request failed
- ResponseSerializationFailed: The serialization of the response failed
- Unknown: Unknow error happen
*/
@objc public enum WordPressOrgXMLRPCApiError: Int, Error {
case requestSerializationFailed
case responseSerializationFailed
case unknown
}
| gpl-2.0 | 9babe63f04fc4d39f3a9ba119c683166 | 44.484568 | 193 | 0.655629 | 5.745419 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift | 81 | 2178 | //
// UINavigationController+Rx.swift
// RxCocoa
//
// Created by Diogo on 13/04/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
extension UINavigationController {
/// Factory method that enables subclasses to implement their own `delegate`.
///
/// - returns: Instance of delegate proxy that wraps `delegate`.
public func createRxDelegateProxy() -> RxNavigationControllerDelegateProxy {
return RxNavigationControllerDelegateProxy(parentObject: self)
}
}
extension Reactive where Base: UINavigationController {
public typealias ShowEvent = (viewController: UIViewController, animated: Bool)
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy {
return RxNavigationControllerDelegateProxy.proxyForObject(base)
}
/// Reactive wrapper for delegate method `navigationController(:willShow:animated:)`.
public var willShow: ControlEvent<ShowEvent> {
let source: Observable<ShowEvent> = delegate
.methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:)))
.map { arg in
let viewController = try castOrThrow(UIViewController.self, arg[1])
let animated = try castOrThrow(Bool.self, arg[2])
return (viewController, animated)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `navigationController(:didShow:animated:)`.
public var didShow: ControlEvent<ShowEvent> {
let source: Observable<ShowEvent> = delegate
.methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:)))
.map { arg in
let viewController = try castOrThrow(UIViewController.self, arg[1])
let animated = try castOrThrow(Bool.self, arg[2])
return (viewController, animated)
}
return ControlEvent(events: source)
}
}
#endif
| mit | 503eefb4e4ec6eb5f08773de3463067a | 35.283333 | 112 | 0.684428 | 5.195704 | false | false | false | false |
Peekazoo/Peekazoo-iOS | Peekazoo/PeekazooTests/Test Doubles/CapturingHomepageServiceLoadingDelegate.swift | 1 | 908 | //
// CapturingHomepageServiceLoadingDelegate.swift
// Peekazoo
//
// Created by Thomas Sherwood on 16/05/2017.
// Copyright © 2017 Peekazoo. All rights reserved.
//
import Peekazoo
class CapturingHomepageServiceLoadingDelegate: HomepageServiceLoadingDelegate {
private(set) var didFinishLoadingInvoked = false
private(set) var capturedHomepageItems: [HomepageItem]?
func homepageServiceDidLoadSuccessfully(content: [HomepageItem]) {
didFinishLoadingInvoked = true
capturedHomepageItems = content
}
private(set) var didFailToLoadInvoked = false
func homepageServiceDidFailToLoad() {
didFailToLoadInvoked = true
}
func capturedItemsEqual<T>(to items: [T]) -> Bool where T: HomepageItem, T: Equatable {
guard let castedItems = capturedHomepageItems as? [T] else { return false }
return items.elementsEqual(castedItems)
}
}
| apache-2.0 | a1ba83b1ab189f0ade9da5005c4464f2 | 29.233333 | 91 | 0.727674 | 4.535 | false | false | false | false |
groue/GRDB.swift | Tests/GRDBTests/AssociationHasManySQLTests.swift | 1 | 56575 | import XCTest
import GRDB
/// Test SQL generation
class AssociationHasManySQLTests: GRDBTestCase {
func testSingleColumnNoForeignKeyNoPrimaryKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var id: Int?
var rowid: Int?
func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["rowid"] = rowid
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("id", .integer)
}
try db.create(table: "children") { t in
t.column("parentId", .integer)
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."rowid"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."rowid"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."rowid"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."rowid"
""")
try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 2
""")
try assertEqualSQL(db, Parent(id: 1, rowid: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")], to: [Column("id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")], to: [Column("id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil, rowid: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testSingleColumnNoForeignKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var id: Int?
func encode(to container: inout PersistenceContainer) {
container["id"] = id
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("id", .integer).primaryKey()
}
try db.create(table: "children") { t in
t.column("parentId", .integer)
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")], to: [Column("id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")], to: [Column("id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testSingleColumnSingleForeignKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var id: Int?
func encode(to container: inout PersistenceContainer) {
container["id"] = id
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("id", .integer).primaryKey()
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self),
Parent.hasMany(Table(Child.databaseTableName)),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentId")], to: [Column("id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentId")], to: [Column("id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parentId" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testSingleColumnSeveralForeignKeys() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var id: Int?
func encode(to container: inout PersistenceContainer) {
container["id"] = id
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("id", .integer).primaryKey()
}
try db.create(table: "children") { t in
t.column("parent1Id", .integer).references("parents")
t.column("parent2Id", .integer).references("parents")
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent1Id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent1Id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parent1Id" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent1Id")], to: [Column("id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent1Id")], to: [Column("id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parent1Id" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent2Id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent2Id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parent2Id" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent2Id")], to: [Column("id")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent2Id")], to: [Column("id")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT * FROM "children" WHERE "parent2Id" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testCompoundColumnNoForeignKeyNoPrimaryKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var a: Int?
var b: Int?
func encode(to container: inout PersistenceContainer) {
container["a"] = a
container["b"] = b
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "children") { t in
t.column("parentA", .integer)
t.column("parentB", .integer)
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testCompoundColumnNoForeignKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var a: Int?
var b: Int?
func encode(to container: inout PersistenceContainer) {
container["a"] = a
container["b"] = b
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("a", .integer)
t.column("b", .integer)
t.primaryKey(["a", "b"])
}
try db.create(table: "children") { t in
t.column("parentA", .integer)
t.column("parentB", .integer)
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentA"), Column("parentB")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentA"), Column("parentB")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testCompoundColumnSingleForeignKey() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var a: Int?
var b: Int?
func encode(to container: inout PersistenceContainer) {
container["a"] = a
container["b"] = b
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("a", .integer)
t.column("b", .integer)
t.primaryKey(["a", "b"])
}
try db.create(table: "children") { t in
t.column("parentA", .integer)
t.column("parentB", .integer)
t.foreignKey(["parentA", "parentB"], references: "parents")
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self),
Parent.hasMany(Table(Child.databaseTableName)),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentA"), Column("parentB")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentA"), Column("parentB")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testCompoundColumnSeveralForeignKeys() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
var a: Int?
var b: Int?
func encode(to container: inout PersistenceContainer) {
container["a"] = a
container["b"] = b
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("a", .integer)
t.column("b", .integer)
t.primaryKey(["a", "b"])
}
try db.create(table: "children") { t in
t.column("parent1A", .integer)
t.column("parent1B", .integer)
t.column("parent2A", .integer)
t.column("parent2B", .integer)
t.foreignKey(["parent1A", "parent1B"], references: "parents")
t.foreignKey(["parent2A", "parent2B"], references: "parents")
}
}
try dbQueue.inDatabase { db in
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent1A"), Column("parent1B")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent1A"), Column("parent1B")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent2A"), Column("parent2B")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent2A"), Column("parent2B")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
for association in [
Parent.hasMany(Child.self,
using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])),
Parent.hasMany(Table(Child.databaseTableName),
using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])),
] {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().including(optional: association), """
SELECT "parents".*, "children".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parents".* \
FROM "parents" \
JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent.all().joining(optional: association), """
SELECT "parents".* \
FROM "parents" \
LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")
""")
try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """
SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2)
""")
try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """
SELECT * FROM "children" WHERE 0
""")
}
}
}
func testForeignKeyDefinitionFromColumn() {
// This test pass if code compiles
struct Parent : TableRecord {
static let databaseTableName = "parents"
enum Columns {
static let id = Column("id")
}
static let child1 = hasMany(Child.self, using: Child.ForeignKeys.parent1)
static let child2 = hasMany(Child.self, using: Child.ForeignKeys.parent2)
}
struct Child : TableRecord {
static let databaseTableName = "children"
enum Columns {
static let parentId = Column("parentId")
}
enum ForeignKeys {
static let parent1 = ForeignKey([Columns.parentId])
static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id])
}
}
}
func testAssociationFilteredByOtherAssociation() throws {
struct Toy: TableRecord { }
struct Child: TableRecord {
static let toy = hasOne(Toy.self)
static let parent = belongsTo(Parent.self)
}
struct Parent: TableRecord, EncodableRecord {
static let children = hasMany(Child.self)
var id: Int?
func encode(to container: inout PersistenceContainer) {
container["id"] = id
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
t.column("childId", .integer).references("child")
}
}
try dbQueue.inDatabase { db in
do {
let association = Parent.children.joining(required: Child.toy)
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".* \
FROM "parent" JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "toy" ON "toy"."childId" = "child"."id" \
WHERE "child"."parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "toy" ON "toy"."childId" = "child"."id" \
WHERE 0
""")
}
do {
// not a realistic use case, but testable anyway
let association = Parent.children.joining(required: Child.parent)
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parent1".*, "child".* \
FROM "parent" "parent1" \
JOIN "child" ON "child"."parentId" = "parent1"."id" \
JOIN "parent" "parent2" ON "parent2"."id" = "child"."parentId"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent1".* \
FROM "parent" "parent1" \
JOIN "child" ON "child"."parentId" = "parent1"."id" \
JOIN "parent" "parent2" ON "parent2"."id" = "child"."parentId"
""")
try assertEqualSQL(db, Parent(id: 1).request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "parent" ON "parent"."id" = "child"."parentId" \
WHERE "child"."parentId" = 1
""")
try assertEqualSQL(db, Parent(id: nil).request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "parent" ON "parent"."id" = "child"."parentId" \
WHERE 0
""")
}
}
}
}
| mit | 13dcdd4e33ab02bfbdb37374db3aece9 | 48.54028 | 127 | 0.455625 | 5.163837 | false | false | false | false |
studyYF/SingleSugar | SingleSugar/SingleSugar/Classes/Tool(工具)/YFHTTPRequestTool.swift | 1 | 6961 | //
// YFHTTPRequestTool.swift
// SingleSugar
//
// Created by YangFan on 2017/4/14.
// Copyright © 2017年 YangFan. All rights reserved.
// 网络请求工具
import Foundation
import Alamofire
import SwiftyJSON
import SVProgressHUD
class YFHTTPRequestTool {
///单例
static let shareNetTool = YFHTTPRequestTool()
/// 网络请求基本方法
///
/// - Parameters:
/// - method: 请求方式
/// - url: 网址
/// - param: 参数
/// - finished: 成功返回
func baseRequest(_ url: String, param: [String:Any]? = nil, finished: @escaping(Any) -> ()) {
Alamofire.request(url, parameters: param).responseJSON { (response) in
//判断是否请求成功
guard response.result.isSuccess else {
SVProgressHUD.showError(withStatus: "加载失败")
return
}
//请求成功后,如果有数据,将数据返回
if let value = response.result.value {
finished(value)
}
}
}
/// 获取单糖数据
///
/// - Parameters:
/// - id: 标题栏id
/// - finished: 成功返回
func momosacchrideData(id: Int, finished: @escaping (_ monoItems: [YFMonosacchrideItem]) -> ()) {
let url = baseURL + "v1/channels/\(id)/items"
let param = ["gender": 1,
"generation": 1,
"limit": 20,
"offset": 0]
baseRequest(url, param: param) { (response) in
//判断返回的数据是否正确
let dict = JSON(response)
let code = dict["code"].intValue
let message = dict["message"].stringValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
let data = dict["data"].dictionary
if let items = data?["items"]?.arrayObject {
var monosacchrideItems = [YFMonosacchrideItem]()
for item in items {
let monoItem = YFMonosacchrideItem(dict: item as! [String : AnyObject])
monosacchrideItems.append(monoItem)
}
finished(monosacchrideItems)
}
}
}
/// 获取单糖标题数据
///
/// - Parameter finished: 完成回调
func monosacchrideTitleData(_ finished: @escaping(_ titleItems: [YFMonoTitleItem]) -> ()) {
let url = baseURL + "v2/channels/preset"
let param = ["gender": 1,
"generation": 1]
baseRequest(url, param: param) { (response) in
let dict = JSON(response)
let code = dict["code"].intValue
let message = dict["message"].stringValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
let data = dict["data"].dictionary
if let titles = data?["channels"]?.arrayObject {
var titleItems = [YFMonoTitleItem]()
for item in titles {
titleItems.append(YFMonoTitleItem(dict: item as! [String : Any]))
}
finished(titleItems)
}
}
}
/// 请求单品数据
///
/// - Parameter finished: 数据回调
func singleProductItem(finished: @escaping([YFSinglePItem]) -> ()) {
let url = baseURL + "v2/items"
let param = ["gender" : 1,
"generation" : 1,
"limit" : 20,
"offset" : 0
]
baseRequest(url, param: param) { (response) in
let dict = JSON(response)
let code = dict["code"].intValue
let message = dict["message"].stringValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
let data = dict["data"].dictionary
if let items = data?["items"]?.arrayObject {
var products = [YFSinglePItem]()
for item in items {
let itemDict = item as! [String : Any]
if let itemData = itemDict["data"] {
products.append(YFSinglePItem(dict: itemData as! [String : Any]))
}
}
finished(products)
}
}
}
/// 获取单品详情数据
///
/// - Parameters:
/// - id: 商品id
/// - finished: 返回数组
func singleProductDetail(id: Int, finished: @escaping(YFSingleProductDetailItem) -> ()) {
let url = baseURL + "v2/items/\(id)"
baseRequest(url) { (response) in
let data = JSON(response)
let message = data["message"].stringValue
let code = data["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
if let items = data["data"].dictionaryObject {
let item = YFSingleProductDetailItem(dict: items as [String : AnyObject])
finished(item)
}
}
}
/// 请求评论数据
///
/// - Parameters:
/// - id: 商品id
/// - finished:
func loadComment(id: Int, finished: @escaping([YFCommentItem]) -> ()) {
let url = baseURL + "v2/items/\(id)/comments"
let params = ["limit": 20,
"offset": 0]
baseRequest(url, param: params) { (response) in
let dict = JSON(response)
let message = dict["message"].stringValue
let code = dict["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
if let data = dict["data"].dictionary {
if let commentData = data["comments"]?.arrayObject {
var commentItems = [YFCommentItem]()
for item in commentData {
commentItems.append(YFCommentItem(dict: item as! [String : AnyObject]))
}
finished(commentItems)
}
}
}
}
func classifyData(_ limit: Int, finished: @escaping([YFClassifyItem]) -> ()) {
let url = baseURL + "v1/collections"
let params = ["limit": limit,
"offset": 0]
baseRequest(url, param: params) { (response) in
let dict = JSON(response)
let message = dict["message"].stringValue
let code = dict["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: message)
return
}
}
}
}
| apache-2.0 | e168b8ab51942f568797484c6d40124e | 30.055556 | 101 | 0.495826 | 4.655101 | false | false | false | false |
Jnosh/swift | test/APINotes/basic.swift | 8 | 1082 | // RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks
import APINotesTest
import APINotesFrameworkTest
#if _runtime(_ObjC)
extension A {
func implicitlyObjC() { }
}
func testSelectors(a: AnyObject) {
a.implicitlyObjC?() // okay: would complain without SwiftObjCMembers
}
#endif
func testSwiftName() {
moveTo(x: 0, y: 0, z: 0)
moveTo(0, 0, 0) // expected-error{{missing argument labels 'x:y:z:' in call}}
_ = global
_ = ANTGlobalValue // expected-error{{'ANTGlobalValue' has been renamed to 'global'}}
let ps = Point(x: 0.0, y: 0.0)
let ps2 = PointStruct(x: 0.0, y: 0.0) // expected-error{{'PointStruct' has been renamed to 'Point'}}
let r: Real = 0.0
let r2: real_t = 0.0 // expected-error{{'real_t' has been renamed to 'Real'}}
let rect: Rect
let rect2: RectStruct // expected-error{{'RectStruct' has been renamed to 'Rect'}}
let d: Double = __will_be_private
// From APINotesFrameworkTest.
jumpTo(x: 0, y: 0, z: 0)
jumpTo(0, 0, 0) // expected-error{{missing argument labels 'x:y:z:' in call}}
}
| apache-2.0 | 0f9e18284e62ced0f2cd2c1580d72bb3 | 29.914286 | 102 | 0.670055 | 3.127168 | false | true | false | false |
achernoprudov/PagedViewContainer | Source/PageMenuCoordinator.swift | 1 | 1863 | //
// PagingMenuCoordinator.swift
// PagingMenuView
//
// Created by Андрей Чернопрудов on 03/03/2017.
// Copyright © 2017 Naumen. All rights reserved.
//
import UIKit
protocol PageCoordinatorProtocol: class {
var currentPage: Int { get }
var enabledItems: [PageItem] { get }
func select(page index: Int)
func select(pageInMenu index: Int)
func select(pageInContainer index: Int)
func set(page index: Int, isEnabled: Bool)
func isEnabled(page: Int) -> Bool
}
class PageCoordinator: PageCoordinatorProtocol {
var items: [PageItem] = []
var currentPage: Int = 0
weak var menu: PageMenu?
weak var container: PageContainer?
var enabledItems: [PageItem] {
return items.filter { $0.isEnabled }
}
func setup(with items: [PageItem]) {
self.items = items
correctCurrentPageIndex()
}
func select(page index: Int) {
currentPage = index
select(pageInMenu: index)
select(pageInContainer: index)
}
func select(pageInMenu index: Int) {
menu?.setActive(page: index)
}
func select(pageInContainer index: Int) {
container?.setActive(page: index)
}
func set(page index: Int, isEnabled: Bool) {
items[index].isEnabled = isEnabled
correctCurrentPageIndex()
let enabledItems = self.enabledItems
UIView.animate(withDuration: 0.3) {
self.menu?.setup(withItems: enabledItems)
self.container?.setup(with: enabledItems)
}
}
func isEnabled(page: Int) -> Bool {
return items[page].isEnabled
}
private func correctCurrentPageIndex() {
if currentPage >= enabledItems.count {
currentPage = 0
}
}
}
| mit | 47c317af8520789847c54dfefa2e696a | 22.0625 | 53 | 0.601626 | 4.320843 | false | false | false | false |
iOS-mamu/SS | P/Pods/PSOperations/PSOperations/ReachabilityCondition.swift | 1 | 3293 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
#if !os(watchOS)
import Foundation
import SystemConfiguration
/**
This is a condition that performs a very high-level reachability check.
It does *not* perform a long-running reachability check, nor does it respond to changes in reachability.
Reachability is evaluated once when the operation to which this is attached is asked about its readiness.
*/
public struct ReachabilityCondition: OperationCondition {
public static let hostKey = "Host"
public static let name = "Reachability"
public static let isMutuallyExclusive = false
let host: URL
public init(host: URL) {
self.host = host
}
public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? {
return nil
}
public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) {
ReachabilityController.requestReachability(host) { reachable in
if reachable {
completion(.satisfied)
}
else {
let error = NSError(code: .conditionFailed, userInfo: [
OperationConditionKey: type(of: self).name,
type(of: self).hostKey: self.host
])
completion(.failed(error))
}
}
}
}
/// A private singleton that maintains a basic cache of `SCNetworkReachability` objects.
private class ReachabilityController {
static var reachabilityRefs = [String: SCNetworkReachability]()
static let reachabilityQueue = DispatchQueue(label: "Operations.Reachability", attributes: [])
static func requestReachability(_ url: URL, completionHandler: @escaping (Bool) -> Void) {
if let host = url.host {
reachabilityQueue.async {
var ref = self.reachabilityRefs[host]
if ref == nil {
let hostString = host as NSString
ref = SCNetworkReachabilityCreateWithName(nil, hostString.utf8String!)
}
if let ref = ref {
self.reachabilityRefs[host] = ref
var reachable = false
var flags: SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(ref, &flags) {
/*
Note that this is a very basic "is reachable" check.
Your app may choose to allow for other considerations,
such as whether or not the connection would require
VPN, a cellular connection, etc.
*/
reachable = flags.contains(.reachable)
}
completionHandler(reachable)
}
else {
completionHandler(false)
}
}
}
else {
completionHandler(false)
}
}
}
#endif
| mit | 01cdbfd98e5be4cc0a1c1b7a009c80ab | 33.28125 | 120 | 0.569128 | 5.794014 | false | false | false | false |
tache/SwifterSwift | Sources/Extensions/Foundation/URLExtensions.swift | 1 | 1323 | //
// URLExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 03/02/2017.
// Copyright © 2017 SwifterSwift
//
import Foundation
// MARK: - Methods
public extension URL {
/// SwifterSwift: URL with appending query parameters.
///
/// let url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendingQueryParameters(params) -> "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
/// - Returns: URL with appending given query parameters.
public func appendingQueryParameters(_ parameters: [String: String]) -> URL {
var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
var items = urlComponents.queryItems ?? []
items += parameters.map({ URLQueryItem(name: $0, value: $1) })
urlComponents.queryItems = items
return urlComponents.url!
}
/// SwifterSwift: Append query parameters to URL.
///
/// var url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendQueryParameters(params)
/// print(url) // prints "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
public mutating func appendQueryParameters(_ parameters: [String: String]) {
self = appendingQueryParameters(parameters)
}
}
| mit | 25f2eda104b181e0f581d95bf2741552 | 30.47619 | 84 | 0.687595 | 3.631868 | false | false | false | false |
Composed/TagListView | TagListView/TagListView.swift | 1 | 7391 | //
// TagListView.swift
// TagListViewDemo
//
// Created by Dongyuan Liu on 2015-05-09.
// Copyright (c) 2015 Ela. All rights reserved.
//
import UIKit
@objc public protocol TagListViewDelegate {
optional func tagPressed(title: String, tagView: TagView, sender: TagListView) -> Void
}
@IBDesignable
public class TagListView: UIView {
@IBInspectable public var textColor: UIColor = UIColor.whiteColor() {
didSet {
for tagView in tagViews {
tagView.textColor = textColor
}
}
}
@IBInspectable public var highlightedTextColor: UIColor = UIColor.whiteColor() {
didSet {
for tagView in tagViews {
tagView.highlightedTextColor = highlightedTextColor
}
}
}
@IBInspectable public var tagBackgroundColor: UIColor = UIColor.grayColor() {
didSet {
for tagView in tagViews {
tagView.tagBackgroundColor = tagBackgroundColor
}
}
}
@IBInspectable public var tagSelectedBackgroundColor: UIColor = UIColor.redColor() {
didSet {
for tagView in tagViews {
tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor
}
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
for tagView in tagViews {
tagView.cornerRadius = cornerRadius
}
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
for tagView in tagViews {
tagView.borderWidth = borderWidth
}
}
}
@IBInspectable public var borderColor: UIColor? {
didSet {
for tagView in tagViews {
tagView.borderColor = borderColor
}
}
}
@IBInspectable public var highlightedBorderColor: UIColor? {
didSet {
for tagView in tagViews {
tagView.highlightedBorderColor = highlightedBorderColor
}
}
}
@IBInspectable public var paddingY: CGFloat = 2 {
didSet {
for tagView in tagViews {
tagView.paddingY = paddingY
}
rearrangeViews()
}
}
@IBInspectable public var paddingX: CGFloat = 5 {
didSet {
for tagView in tagViews {
tagView.paddingX = paddingX
}
rearrangeViews()
}
}
@IBInspectable public var marginY: CGFloat = 2 {
didSet {
rearrangeViews()
}
}
@IBInspectable public var marginX: CGFloat = 5 {
didSet {
rearrangeViews()
}
}
public var textFont: UIFont = UIFont.systemFontOfSize(12) {
didSet {
for tagView in tagViews {
tagView.textFont = textFont
}
rearrangeViews()
}
}
@IBOutlet public var delegate: TagListViewDelegate?
var tagViews: [TagView] = []
var rowViews: [UIView] = []
var tagViewHeight: CGFloat = 0
var rows = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: - Interface Builder
public override func prepareForInterfaceBuilder() {
addTag("Welcome")
addTag("to")
addTag("TagListView").selected = true
}
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
rearrangeViews()
}
private func rearrangeViews() {
for tagView in tagViews {
tagView.removeFromSuperview()
}
for rowView in rowViews {
rowView.removeFromSuperview()
}
rowViews.removeAll(keepCapacity: true)
var currentRow = 0
var currentRowTagCount = 0
var currentRowWidth: CGFloat = 0
var currentRowView: UIView!
for tagView in tagViews {
tagView.frame.size = tagView.intrinsicContentSize()
tagViewHeight = tagView.frame.height
if currentRow == 0 || currentRowWidth + tagView.frame.width + marginX > frame.width {
currentRow += 1
currentRowWidth = 0
currentRowTagCount = 0
currentRowView = UIView()
currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY)
rowViews.append(currentRowView)
addSubview(currentRowView)
}
tagView.frame.origin = CGPoint(x: currentRowWidth, y: 0)
currentRowView.addSubview(tagView)
currentRowTagCount++
currentRowWidth += tagView.frame.width + marginX
currentRowView.frame.origin.x = (frame.size.width - (currentRowWidth - marginX)) / 2
currentRowView.frame.size.width = currentRowWidth
currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.size.height)
}
rows = currentRow
}
// MARK: - Manage tags
public override func intrinsicContentSize() -> CGSize {
var height = CGFloat(rows) * (tagViewHeight + marginY)
if rows > 0 {
height -= marginY
}
return CGSizeMake(frame.width, height)
}
public func addTag(title: String) -> TagView {
let tagView = TagView(title: title)
tagView.textColor = textColor
tagView.highlightedTextColor = highlightedTextColor
tagView.tagBackgroundColor = tagBackgroundColor
tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor
tagView.cornerRadius = cornerRadius
tagView.borderWidth = borderWidth
tagView.borderColor = borderColor
tagView.highlightedBorderColor = highlightedBorderColor
tagView.paddingY = paddingY
tagView.paddingX = paddingX
tagView.textFont = textFont
tagView.addTarget(self, action: "tagPressed:", forControlEvents: UIControlEvents.TouchUpInside)
return addTagView(tagView)
}
public func addTagView(tagView: TagView) -> TagView {
tagViews.append(tagView)
rearrangeViews()
return tagView
}
public func removeTag(title: String) {
// loop the array in reversed order to remove items during loop
for index in (tagViews.count - 1).stride(through: 0, by: -1) {
let tagView = tagViews[index]
if tagView.currentTitle == title {
removeTagView(tagView)
}
}
}
public func removeTagView(tagView: TagView) {
tagView.removeFromSuperview()
if let index = tagViews.indexOf(tagView) {
tagViews.removeAtIndex(index)
}
rearrangeViews()
}
public func removeAllTags() {
for tagView in tagViews {
tagView.removeFromSuperview()
}
tagViews = []
rearrangeViews()
}
public func selectedTags() -> [TagView] {
return tagViews.filter() { $0.selected == true }
}
// MARK: - Events
func tagPressed(sender: TagView!) {
sender.onTap?(sender)
delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self)
}
}
| mit | 860df30eb1226155d6c860423fb8d9dc | 27.871094 | 103 | 0.5734 | 5.367466 | false | false | false | false |
Antondomashnev/Sourcery | Pods/XcodeEdit/Sources/XCProjectFile.swift | 1 | 5572 | //
// XCProjectFile.swift
// XcodeEdit
//
// Created by Tom Lokhorst on 2015-08-12.
// Copyright (c) 2015 nonstrict. All rights reserved.
//
import Foundation
enum ProjectFileError : Error, CustomStringConvertible {
case invalidData
case notXcodeproj
case missingPbxproj
var description: String {
switch self {
case .invalidData:
return "Data in .pbxproj file not in expected format"
case .notXcodeproj:
return "Path is not a .xcodeproj package"
case .missingPbxproj:
return "project.pbxproj file missing"
}
}
}
public class AllObjects {
var dict: [String: PBXObject] = [:]
var fullFilePaths: [String: Path] = [:]
func object<T : PBXObject>(_ key: String) -> T {
let obj = dict[key]!
if let t = obj as? T {
return t
}
return T(id: key, dict: obj.dict as AnyObject, allObjects: self)
}
}
public class XCProjectFile {
public let project: PBXProject
let dict: JsonObject
var format: PropertyListSerialization.PropertyListFormat
let allObjects = AllObjects()
public convenience init(xcodeprojURL: URL) throws {
let pbxprojURL = xcodeprojURL.appendingPathComponent("project.pbxproj", isDirectory: false)
let data = try Data(contentsOf: pbxprojURL)
try self.init(propertyListData: data)
}
public convenience init(propertyListData data: Data) throws {
let options = PropertyListSerialization.MutabilityOptions()
var format: PropertyListSerialization.PropertyListFormat = PropertyListSerialization.PropertyListFormat.binary
let obj = try PropertyListSerialization.propertyList(from: data, options: options, format: &format)
guard let dict = obj as? JsonObject else {
throw ProjectFileError.invalidData
}
self.init(dict: dict, format: format)
}
init(dict: JsonObject, format: PropertyListSerialization.PropertyListFormat) {
self.dict = dict
self.format = format
let objects = dict["objects"] as! [String: JsonObject]
for (key, obj) in objects {
allObjects.dict[key] = XCProjectFile.createObject(key, dict: obj, allObjects: allObjects)
}
let rootObjectId = dict["rootObject"]! as! String
let projDict = objects[rootObjectId]!
self.project = PBXProject(id: rootObjectId, dict: projDict as AnyObject, allObjects: allObjects)
self.allObjects.fullFilePaths = paths(self.project.mainGroup, prefix: "")
}
static func projectName(from url: URL) throws -> String {
let subpaths = url.pathComponents
guard let last = subpaths.last,
let range = last.range(of: ".xcodeproj")
else {
throw ProjectFileError.notXcodeproj
}
return last.substring(to: range.lowerBound)
}
static func createObject(_ id: String, dict: JsonObject, allObjects: AllObjects) -> PBXObject {
let isa = dict["isa"] as? String
if let isa = isa,
let type = types[isa] {
return type.init(id: id, dict: dict as AnyObject, allObjects: allObjects)
}
// Fallback
assertionFailure("Unknown PBXObject subclass isa=\(String(describing: isa))")
return PBXObject(id: id, dict: dict as AnyObject, allObjects: allObjects)
}
func paths(_ current: PBXGroup, prefix: String) -> [String: Path] {
var ps: [String: Path] = [:]
for file in current.fileRefs {
switch file.sourceTree {
case .group:
switch current.sourceTree {
case .absolute:
ps[file.id] = .absolute(prefix + "/" + file.path!)
case .group:
ps[file.id] = .relativeTo(.sourceRoot, prefix + "/" + file.path!)
case .relativeTo(let sourceTreeFolder):
ps[file.id] = .relativeTo(sourceTreeFolder, prefix + "/" + file.path!)
}
case .absolute:
ps[file.id] = .absolute(file.path!)
case let .relativeTo(sourceTreeFolder):
ps[file.id] = .relativeTo(sourceTreeFolder, file.path!)
}
}
for group in current.subGroups {
if let path = group.path {
let str: String
switch group.sourceTree {
case .absolute:
str = path
case .group:
str = prefix + "/" + path
case .relativeTo(.sourceRoot):
str = path
case .relativeTo(.buildProductsDir):
str = path
case .relativeTo(.developerDir):
str = path
case .relativeTo(.sdkRoot):
str = path
}
ps += paths(group, prefix: str)
}
else {
ps += paths(group, prefix: prefix)
}
}
return ps
}
}
let types: [String: PBXObject.Type] = [
"PBXProject": PBXProject.self,
"PBXContainerItemProxy": PBXContainerItemProxy.self,
"PBXBuildFile": PBXBuildFile.self,
"PBXCopyFilesBuildPhase": PBXCopyFilesBuildPhase.self,
"PBXFrameworksBuildPhase": PBXFrameworksBuildPhase.self,
"PBXHeadersBuildPhase": PBXHeadersBuildPhase.self,
"PBXResourcesBuildPhase": PBXResourcesBuildPhase.self,
"PBXShellScriptBuildPhase": PBXShellScriptBuildPhase.self,
"PBXSourcesBuildPhase": PBXSourcesBuildPhase.self,
"PBXBuildStyle": PBXBuildStyle.self,
"XCBuildConfiguration": XCBuildConfiguration.self,
"PBXAggregateTarget": PBXAggregateTarget.self,
"PBXNativeTarget": PBXNativeTarget.self,
"PBXTargetDependency": PBXTargetDependency.self,
"XCConfigurationList": XCConfigurationList.self,
"PBXReference": PBXReference.self,
"PBXReferenceProxy": PBXReferenceProxy.self,
"PBXFileReference": PBXFileReference.self,
"PBXGroup": PBXGroup.self,
"PBXVariantGroup": PBXVariantGroup.self,
"XCVersionGroup": XCVersionGroup.self
]
| mit | 590d3693d26bac78a2f9d029c4014491 | 27.574359 | 114 | 0.674623 | 4.250191 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILEReadLocalSupportedFeatures.swift | 1 | 1965 | //
// HCILEReadLocalSupportedFeaturesReturn.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/15/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Read Local Supported Features Command
///
/// This command requests the list of the supported LE features for the Controller.
func lowEnergyReadLocalSupportedFeatures(timeout: HCICommandTimeout = .default) async throws -> LowEnergyFeatureSet {
let returValue = try await deviceRequest(HCILEReadLocalSupportedFeatures.self, timeout: timeout)
return returValue.features
}
}
// MARK: - Return parameter
/// LE Read Local Supported Features Command
///
/// This command requests the list of the supported LE features for the Controller.
@frozen
public struct HCILEReadLocalSupportedFeatures: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.readLocalSupportedFeatures // 0x0003
public static let length = 8
public let features: LowEnergyFeatureSet
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let featuresRawValue = UInt64(littleEndian: UInt64(bytes: (data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7])))
self.features = LowEnergyFeatureSet(rawValue: featuresRawValue)
}
}
| mit | a2aa5752b9ea999b42cf5c0cbddc44b8 | 34.071429 | 121 | 0.526477 | 5.74269 | false | false | false | false |
yisimeng/YSMFactory-swift | YSMFactory-swift/BaseClass/ViewController/YSMNavigationController.swift | 1 | 983 | //
// YSMNavigationController.swift
// YSMFactory-swift
//
// Created by 忆思梦 on 2016/12/19.
// Copyright © 2016年 忆思梦. All rights reserved.
//
import UIKit
class YSMNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
guard let targets = interactivePopGestureRecognizer!.value(forKey: "_targets") as? [NSObject] else { return }
let targetObjc = targets[0]
let target = targetObjc.value(forKey: "target")
let action = Selector(("handleNavigationTransition:"))
let pan = UIPanGestureRecognizer(target: target, action: action)
view.addGestureRecognizer(pan)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if viewControllers.count != 0 {
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
}
| mit | 31835fd6d70cf4d68fb4829a8e6ba06a | 30.225806 | 118 | 0.673554 | 4.81592 | false | false | false | false |
hollance/swift-algorithm-club | Dijkstra Algorithm/VisualizedDijkstra.playground/Sources/GraphView.swift | 4 | 10463 | import UIKit
public class GraphView: UIView {
private var graph: Graph
private var panningView: VertexView? = nil
private var graphColors = GraphColors.sharedInstance
public init(frame: CGRect, graph: Graph) {
self.graph = graph
super.init(frame: frame)
backgroundColor = graphColors.graphBackgroundColor
layer.cornerRadius = 15
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func removeGraph() {
for vertex in graph.vertices {
if let view = vertex.view {
view.removeFromSuperview()
vertex.view = nil
}
}
for vertex in graph.vertices {
for edge in vertex.edges {
if let edgeRepresentation = edge.edgeRepresentation {
edgeRepresentation.layer.removeFromSuperlayer()
edgeRepresentation.label.removeFromSuperview()
edge.edgeRepresentation = nil
}
}
}
}
public func createNewGraph() {
setupVertexViews()
setupEdgeRepresentations()
addGraph()
}
public func reset() {
for vertex in graph.vertices {
vertex.edges.forEach { $0.edgeRepresentation?.setDefaultColor() }
vertex.setDefaultColor()
}
}
private func addGraph() {
for vertex in graph.vertices {
for edge in vertex.edges {
if let edgeRepresentation = edge.edgeRepresentation {
layer.addSublayer(edgeRepresentation.layer)
addSubview(edgeRepresentation.label)
}
}
}
for vertex in graph.vertices {
if let view = vertex.view {
addSubview(view)
}
}
}
private func setupVertexViews() {
var level = 0
var buildViewQueue = [graph.startVertex!]
let itemWidth: CGFloat = 40
while !buildViewQueue.isEmpty {
let levelItemsCount = CGFloat(buildViewQueue.count)
let xStep = (frame.width - levelItemsCount * itemWidth) / (levelItemsCount + 1)
var previousVertexMaxX: CGFloat = 0.0
for vertex in buildViewQueue {
let x: CGFloat = previousVertexMaxX + xStep
let y: CGFloat = CGFloat(level * 100)
previousVertexMaxX = x + itemWidth
let frame = CGRect(x: x, y: y, width: itemWidth, height: itemWidth)
let vertexView = VertexView(frame: frame)
vertex.view = vertexView
vertexView.vertex = vertex
vertex.view?.setIdLabel(text: vertex.identifier)
vertex.view?.setPathLengthLabel(text: "\(vertex.pathLengthFromStart)")
vertex.view?.addTarget(self, action: #selector(didTapVertex(sender:)), for: .touchUpInside)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
vertex.view?.addGestureRecognizer(panGesture)
}
level += 1
buildViewQueue = graph.vertices.filter { $0.level == level }
}
}
private var movingVertexInputEdges: [EdgeRepresentation] = []
private var movingVertexOutputEdges: [EdgeRepresentation] = []
@objc private func handlePan(recognizer: UIPanGestureRecognizer) {
guard let vertexView = recognizer.view as? VertexView, let vertex = vertexView.vertex else {
return
}
if panningView != nil {
if panningView != vertexView {
return
}
}
switch recognizer.state {
case .began:
let movingVertexViewFrame = vertexView.frame
let sizedVertexView = CGRect(x: movingVertexViewFrame.origin.x - 10,
y: movingVertexViewFrame.origin.y - 10,
width: movingVertexViewFrame.width + 20,
height: movingVertexViewFrame.height + 20)
vertex.edges.forEach { edge in
if let edgeRepresentation = edge.edgeRepresentation{
if sizedVertexView.contains(edgeRepresentation.layer.startPoint!) {
movingVertexOutputEdges.append(edgeRepresentation)
} else {
movingVertexInputEdges.append(edgeRepresentation)
}
}
}
panningView = vertexView
case .changed:
if movingVertexOutputEdges.isEmpty && movingVertexInputEdges.isEmpty {
return
}
let translation = recognizer.translation(in: self)
if vertexView.frame.origin.x + translation.x <= 0
|| vertexView.frame.origin.y + translation.y <= 0
|| (vertexView.frame.origin.x + vertexView.frame.width + translation.x) >= frame.width
|| (vertexView.frame.origin.y + vertexView.frame.height + translation.y) >= frame.height {
break
}
movingVertexInputEdges.forEach { edgeRepresentation in
let originalLabelCenter = edgeRepresentation.label.center
edgeRepresentation.label.center = CGPoint(x: originalLabelCenter.x + translation.x * 0.625,
y: originalLabelCenter.y + translation.y * 0.625)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
let newPath = path(fromEdgeRepresentation: edgeRepresentation, movingVertex: vertex, translation: translation, outPath: false)
edgeRepresentation.layer.path = newPath
CATransaction.commit()
}
movingVertexOutputEdges.forEach { edgeRepresentation in
let originalLabelCenter = edgeRepresentation.label.center
edgeRepresentation.label.center = CGPoint(x: originalLabelCenter.x + translation.x * 0.375,
y: originalLabelCenter.y + translation.y * 0.375)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
let newPath = path(fromEdgeRepresentation: edgeRepresentation, movingVertex: vertex, translation: translation, outPath: true)
edgeRepresentation.layer.path = newPath
CATransaction.commit()
}
vertexView.center = CGPoint(x: vertexView.center.x + translation.x,
y: vertexView.center.y + translation.y)
recognizer.setTranslation(CGPoint.zero, in: self)
case .ended:
movingVertexInputEdges = []
movingVertexOutputEdges = []
panningView = nil
default:
break
}
}
private func path(fromEdgeRepresentation edgeRepresentation: EdgeRepresentation, movingVertex: Vertex, translation: CGPoint, outPath: Bool) -> CGPath {
let bezier = UIBezierPath()
if outPath == true {
bezier.move(to: edgeRepresentation.layer.endPoint!)
let startPoint = CGPoint(x: edgeRepresentation.layer.startPoint!.x + translation.x,
y: edgeRepresentation.layer.startPoint!.y + translation.y)
edgeRepresentation.layer.startPoint = startPoint
bezier.addLine(to: startPoint)
} else {
bezier.move(to: edgeRepresentation.layer.startPoint!)
let endPoint = CGPoint(x: edgeRepresentation.layer.endPoint!.x + translation.x,
y: edgeRepresentation.layer.endPoint!.y + translation.y)
edgeRepresentation.layer.endPoint = endPoint
bezier.addLine(to: endPoint)
}
return bezier.cgPath
}
@objc private func didTapVertex(sender: AnyObject) {
DispatchQueue.main.async {
if self.graph.state == .completed {
for vertex in self.graph.vertices {
vertex.edges.forEach { $0.edgeRepresentation?.setDefaultColor() }
vertex.setVisitedColor()
}
if let vertexView = sender as? VertexView, let vertex = vertexView.vertex {
for (index, pathVertex) in vertex.pathVerticesFromStart.enumerated() {
pathVertex.setCheckingPathColor()
if vertex.pathVerticesFromStart.count > index + 1 {
let nextVertex = vertex.pathVerticesFromStart[index + 1]
if let edge = pathVertex.edges.filter({ $0.neighbor == nextVertex }).first {
edge.edgeRepresentation?.setCheckingColor()
}
}
}
}
} else if self.graph.state == .interactiveVisualization {
if let vertexView = sender as? VertexView, let vertex = vertexView.vertex {
if vertex.visited {
return
} else {
self.graph.didTapVertex(vertex: vertex)
}
}
}
}
}
private func setupEdgeRepresentations() {
var edgeQueue: [Vertex] = [graph.startVertex!]
//BFS
while !edgeQueue.isEmpty {
let currentVertex = edgeQueue.first!
currentVertex.haveAllEdges = true
for edge in currentVertex.edges {
let neighbor = edge.neighbor
let weight = edge.weight
if !neighbor.haveAllEdges {
let edgeRepresentation = EdgeRepresentation(from: currentVertex, to: neighbor, weight: weight)
edge.edgeRepresentation = edgeRepresentation
let index = neighbor.edges.index(where: { $0.neighbor == currentVertex })!
neighbor.edges[index].edgeRepresentation = edgeRepresentation
edgeQueue.append(neighbor)
}
}
edgeQueue.removeFirst()
}
}
}
| mit | ae5588aa65cc2df0afd7c9790b14caa8 | 41.881148 | 155 | 0.56198 | 5.37667 | false | false | false | false |
caoimghgin/HexKit | Pod/Classes/Board.swift | 1 | 5623 | //
// Board.swift
// https://github.com/caoimghgin/HexKit
//
// Copyright © 2015 Kevin Muldoon.
//
// This code is distributed under the terms and conditions of the MIT license.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import UIKit
class Board : UIView, UIGestureRecognizerDelegate {
var artwork = Artwork()
var arena = Arena()
var grid = Grid()
var transit = Transit()
var sceneDelegate = HexKitSceneDelegate?()
init() {
super.init(frame: grid.frame)
// addSubview(artwork)
// addSubview(UIImageView(image: UIImage(imageLiteral: "Tobruk")))
// addSubview(grid)
addSubview(arena)
let panGesture = UIPanGestureRecognizer(target: self, action: "panGestureRecognizerAction:")
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: "tapGestureRecognizerAction:")
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
}
override func drawRect(rect: CGRect) {
}
func tapGestureRecognizerAction(gesture : UITapGestureRecognizer) {
let tile = Touch.tile(gesture)
self.sceneDelegate?.tileWasTapped(tile)
if (tile.units.count > 0) {
let unit = tile.units.first
unit!.superview!.sendSubviewToBack(unit!)
tile.sendUnitToBack(unit!)
Move.prettyStack(tile)
}
}
func panGestureRecognizerAction(gesture : UIPanGestureRecognizer) {
switch gesture.state {
case UIGestureRecognizerState.Possible:
print("Possible")
case UIGestureRecognizerState.Began:
let tile = Touch.tile(gesture)
if (tile.units.count > 0) {
transit = Transit(tile: tile)
transit.departure(tile)
}
self.layer.addSublayer(transit.line)
case UIGestureRecognizerState.Changed:
let state = transit.transit(Touch.tile(gesture))
switch state {
case Transit.State.Allowed:
print("allowed")
case Transit.State.InsufficiantMovementPoints:
gesture.enabled = false
print("InsufficiantMovementPoints error")
case Transit.State.MaximumMovementReached:
gesture.enabled = false
print("MaximumMovementReached error")
case Transit.State.Unexpected:
print("Transit.State.Unexpected")
}
case UIGestureRecognizerState.Ended:
let tile = Touch.tile(gesture)
transit.transit(tile)
transit.end()
_ = Move(transit: transit)
case UIGestureRecognizerState.Cancelled:
/*
move unit back to originating hex and set gesture to enabled
*/
transit.arrival(transit.departing)
gesture.enabled = true
case UIGestureRecognizerState.Failed:
print("failed")
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// return true; /* uncomment to disable UIScrollView scrolling **/
let tile = Touch.tile(touch)
if (tile.units.count > 0) {
let unit = tile.units.first
if (unit?.alliance == HexKit.sharedInstance.turn) {
return true
} else {
return false
}
}
return false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false;
}
}
class Artwork : UIImageView {
}
class Arena: UIView {
}
| mit | 7424a080abdbb10f0249b5bf19706424 | 29.064171 | 172 | 0.576129 | 5.605184 | false | false | false | false |
PoissonBallon/EasyRealm | EasyRealm/Classes/EasyRealmQueue.swift | 1 | 411 | //
// EasyRealmCore.swift
// Pods
//
// Created by Allan Vialatte on 17/02/2017.
//
//
import Foundation
import RealmSwift
internal struct EasyRealmQueue {
let realm:Realm
let queue:DispatchQueue
init?() {
queue = DispatchQueue(label: UUID().uuidString)
var tmp:Realm? = nil
queue.sync { tmp = try? Realm() }
guard let valid = tmp else { return nil }
self.realm = valid
}
}
| mit | fae5f0236b8aeb88511afb5ed6c01101 | 16.125 | 51 | 0.647202 | 3.512821 | false | false | false | false |
debugsquad/nubecero | nubecero/Model/OnboardForm/MOnboardForm.swift | 1 | 5041 | import Foundation
class MOnboardForm
{
enum Method
{
case Register
case Signin
}
let items:[MOnboardFormItem]
let title:String
let buttonMessage:String
let method:Method
weak var itemEmail:MOnboardFormItemEmail!
weak var itemPassword:MOnboardFormItemPassword!
private let kEmailMinLength:Int = 4
private let kPasswordMinLength:Int = 6
class func Register() -> MOnboardForm
{
let method:Method = Method.Register
let title:String = NSLocalizedString("MOnboardForm_titleRegister", comment:"")
let buttonMessage:String = NSLocalizedString("MOnboardForm_buttonRegister", comment:"")
let itemEmail:MOnboardFormItemEmailRegister = MOnboardFormItemEmailRegister()
let itemPassword:MOnboardFormItemPasswordRegister = MOnboardFormItemPasswordRegister()
let itemPassGenerator:MOnboardFormItemPassGenerator = MOnboardFormItemPassGenerator()
let itemRemember:MOnboardFormItemRemember = MOnboardFormItemRemember()
let items:[MOnboardFormItem] = [
itemEmail,
itemPassword,
itemPassGenerator,
itemRemember
]
let model:MOnboardForm = MOnboardForm(
method:method,
items:items,
title:title,
buttonMessage:buttonMessage,
itemEmail:itemEmail,
itemPassword:itemPassword)
return model
}
class func Signin() -> MOnboardForm
{
let method:Method = Method.Signin
let title:String = NSLocalizedString("MOnboardForm_titleSignin", comment:"")
let buttonMessage:String = NSLocalizedString("MOnboardForm_buttonSignin", comment:"")
let itemEmail:MOnboardFormItemEmailSignin = MOnboardFormItemEmailSignin()
let itemPassword:MOnboardFormItemPasswordSignin = MOnboardFormItemPasswordSignin()
let itemRemember:MOnboardFormItemRemember = MOnboardFormItemRemember()
let itemForgot:MOnboardFormItemForgot = MOnboardFormItemForgot()
let items:[MOnboardFormItem] = [
itemEmail,
itemPassword,
itemRemember,
itemForgot
]
let model:MOnboardForm = MOnboardForm(
method:method,
items:items,
title:title,
buttonMessage:buttonMessage,
itemEmail:itemEmail,
itemPassword:itemPassword)
return model
}
private init(method:Method, items:[MOnboardFormItem], title:String, buttonMessage:String, itemEmail:MOnboardFormItemEmail, itemPassword:MOnboardFormItemPassword)
{
self.method = method
self.items = items
self.title = title
self.buttonMessage = buttonMessage
self.itemEmail = itemEmail
self.itemPassword = itemPassword
}
init()
{
fatalError()
}
//MARK: public
func createCredentials(completion:@escaping((MOnboardFormCredentials?, String?) -> ()))
{
let emailMinLength:Int = kEmailMinLength
let passwordMinLength:Int = kPasswordMinLength
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
let credentials:MOnboardFormCredentials?
let errorString:String?
guard
let email:String = self?.itemEmail.email
else
{
credentials = nil
errorString = NSLocalizedString("MOnboardForm_errorEmail", comment:"")
completion(credentials, errorString)
return
}
if email.characters.count < emailMinLength
{
credentials = nil
errorString = NSLocalizedString("MOnboardForm_errorEmailShort", comment:"")
completion(credentials, errorString)
return
}
guard
let password:String = self?.itemPassword.password
else
{
credentials = nil
errorString = NSLocalizedString("MOnboardForm_errorPassword", comment:"")
completion(credentials, errorString)
return
}
if password.characters.count < passwordMinLength
{
credentials = nil
errorString = NSLocalizedString("MOnboardForm_errorPasswordShort", comment:"")
completion(credentials, errorString)
return
}
credentials = MOnboardFormCredentials(
email:email,
password:password)
errorString = nil
completion(credentials, errorString)
}
}
}
| mit | 7acb65ae83777fb707a201279443edbb | 30.905063 | 165 | 0.579052 | 5.841251 | false | false | false | false |
avito-tech/Marshroute | Marshroute/Sources/Transitions/TransitionContexts/PresentationTransitionContext.swift | 1 | 14575 | import UIKit
/// Описание перехода `вперед` на следующий модуль
public struct PresentationTransitionContext {
/// идентификатор перехода
/// для точной отмены нужного перехода и возвращения на предыдущий экран через
/// ```swift
/// undoTransitionWith(transitionId:)
public let transitionId: TransitionId
/// контроллер, на который нужно перейти
public let targetViewController: UIViewController
/// обработчик переходов для модуля, на который нужно перейти
/// (может отличаться от обработчика переходов, ответственного за выполнение текущего перехода)
public private(set) var targetTransitionsHandlerBox: PresentationTransitionTargetTransitionsHandlerBox
/// параметры перехода, на которые нужно держать сильную ссылку (например, обработчик переходов SplitViewController'а)
public let storableParameters: TransitionStorableParameters?
/// параметры запуска анимации прямого перехода
public var presentationAnimationLaunchingContextBox: PresentationAnimationLaunchingContextBox
}
// MARK: - Init
public extension PresentationTransitionContext {
// MARK: - Push
/// Контекст описывает последовательный переход внутри UINavigationController'а
/// если UINavigationController'а не является самым верхним, то переход будет прокинут
/// в самый верхний UINavigationController
init(pushingViewController targetViewController: UIViewController,
animator: NavigationTransitionsAnimator,
transitionId: TransitionId)
{
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .pendingAnimating
self.storableParameters = nil
let animationLaunchingContext = PushAnimationLaunchingContext(
targetViewController: targetViewController,
animator: animator
)
self.presentationAnimationLaunchingContextBox = .push(
launchingContext: animationLaunchingContext
)
}
// MARK: - Modal
/// Контекст описывает переход на простой модальный контроллер
init(presentingModalViewController targetViewController: UIViewController,
targetTransitionsHandler: AnimatingTransitionsHandler,
animator: ModalTransitionsAnimator,
transitionId: TransitionId)
{
marshrouteAssert(
!(targetViewController is UISplitViewController) && !(targetViewController is UITabBarController),
"use presentingModalMasterDetailViewController:targetTransitionsHandler:animator:transitionId:"
)
marshrouteAssert(
!(targetViewController is UINavigationController),
"use presentingModalNavigationController:targetTransitionsHandler:animator:transitionId:"
)
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = NavigationTransitionStorableParameters(
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = ModalPresentationAnimationLaunchingContext(
targetViewController: targetViewController,
animator: animator
)
self.presentationAnimationLaunchingContextBox = .modal(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает переход на модальный контроллер, который нельзя! положить в UINavigationController:
/// UISplitViewController
init(presentingModalMasterDetailViewController targetViewController: UISplitViewController,
targetTransitionsHandler: ContainingTransitionsHandler,
animator: ModalMasterDetailTransitionsAnimator,
transitionId: TransitionId)
{
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .init(containingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = NavigationTransitionStorableParameters(
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = ModalMasterDetailPresentationAnimationLaunchingContext(
targetViewController: targetViewController,
animator: animator
)
self.presentationAnimationLaunchingContextBox = .modalMasterDetail(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает переход на модальный контроллер, который положен в UINavigationController
init(presentingModalViewController targetViewController: UIViewController,
inNavigationController navigationController: UINavigationController,
targetTransitionsHandler: NavigationTransitionsHandlerImpl,
animator: ModalNavigationTransitionsAnimator,
transitionId: TransitionId)
{
marshrouteAssert(
!(targetViewController is UISplitViewController) && !(targetViewController is UITabBarController),
"use presentingModalMasterDetailViewController:targetTransitionsHandler:animator:transitionId:"
)
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = NavigationTransitionStorableParameters(
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = ModalNavigationPresentationAnimationLaunchingContext(
targetNavigationController: navigationController,
targetViewController: targetViewController,
animator: animator
)
self.presentationAnimationLaunchingContextBox = .modalNavigation(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает переход на конечный модальный UINavigationController
/// использовать для MFMailComposeViewController, UIImagePickerController
init(presentingModalEndpointNavigationController navigationController: UINavigationController,
targetTransitionsHandler: NavigationTransitionsHandlerImpl,
animator: ModalEndpointNavigationTransitionsAnimator,
transitionId: TransitionId)
{
self.transitionId = transitionId
self.targetViewController = navigationController
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = NavigationTransitionStorableParameters(
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = ModalEndpointNavigationPresentationAnimationLaunchingContext(
targetNavigationController: navigationController,
animator: animator
)
self.presentationAnimationLaunchingContextBox = .modalEndpointNavigation(
launchingContext: animationLaunchingContext
)
}
// MARK: - Popover
/// Контекст описывает вызов поповера, содержащего простой UIViewController
init(presentingViewController targetViewController: UIViewController,
inPopoverController popoverController: UIPopoverController,
fromRect rect: CGRect,
inView view: UIView,
targetTransitionsHandler: AnimatingTransitionsHandler,
animator: PopoverTransitionsAnimator,
transitionId: TransitionId)
{
self.targetViewController = targetViewController
self.transitionId = transitionId
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = PopoverTransitionStorableParameters(
popoverController: popoverController,
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = PopoverPresentationAnimationLaunchingContext(
transitionStyle: .popoverFromView(sourceView: view, sourceRect: rect),
targetViewController: targetViewController,
popoverController: popoverController,
animator: animator)
self.presentationAnimationLaunchingContextBox = .popover(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает вызов поповера, содержащего контроллер, который положен в UINavigationController
init(presentingViewController targetViewController: UIViewController,
inNavigationController navigationController: UINavigationController,
inPopoverController popoverController: UIPopoverController,
fromRect rect: CGRect,
inView view: UIView,
targetTransitionsHandler: NavigationTransitionsHandlerImpl,
animator: PopoverNavigationTransitionsAnimator,
transitionId: TransitionId)
{
self.targetViewController = targetViewController
self.transitionId = transitionId
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = PopoverTransitionStorableParameters(
popoverController: popoverController,
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = PopoverNavigationPresentationAnimationLaunchingContext(
transitionStyle: .popoverFromView(sourceView: view, sourceRect: rect),
targetViewController: targetViewController,
targetNavigationController: navigationController,
popoverController: popoverController,
animator: animator)
self.presentationAnimationLaunchingContextBox = .popoverNavigation(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает вызов поповера, содержащего простой UIViewController
init(presentingViewController targetViewController: UIViewController,
inPopoverController popoverController: UIPopoverController,
fromBarButtonItem buttonItem: UIBarButtonItem,
targetTransitionsHandler: AnimatingTransitionsHandler,
animator: PopoverTransitionsAnimator,
transitionId: TransitionId)
{
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = PopoverTransitionStorableParameters(
popoverController: popoverController,
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = PopoverPresentationAnimationLaunchingContext(
transitionStyle: .popoverFromBarButtonItem(buttonItem: buttonItem),
targetViewController: targetViewController,
popoverController: popoverController,
animator: animator)
self.presentationAnimationLaunchingContextBox = .popover(
launchingContext: animationLaunchingContext
)
}
/// Контекст описывает вызов поповера, содержащего контроллер, который положен в UINavigationController
init(presentingViewController targetViewController: UIViewController,
inNavigationController navigationController: UINavigationController,
inPopoverController popoverController: UIPopoverController,
fromBarButtonItem buttonItem: UIBarButtonItem,
targetTransitionsHandler: AnimatingTransitionsHandler,
animator: PopoverNavigationTransitionsAnimator,
transitionId: TransitionId)
{
self.transitionId = transitionId
self.targetViewController = targetViewController
self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler)
self.storableParameters = PopoverTransitionStorableParameters(
popoverController: popoverController,
presentedTransitionsHandler: targetTransitionsHandler
)
let animationLaunchingContext = PopoverNavigationPresentationAnimationLaunchingContext(
transitionStyle: .popoverFromBarButtonItem(buttonItem: buttonItem),
targetViewController: targetViewController,
targetNavigationController: navigationController,
popoverController: popoverController,
animator: animator)
self.presentationAnimationLaunchingContextBox = .popoverNavigation(
launchingContext: animationLaunchingContext
)
}
}
// MARK: - Convenience
extension PresentationTransitionContext {
var needsAnimatingTargetTransitionHandler: Bool {
let result = self.targetTransitionsHandlerBox.needsAnimatingTargetTransitionHandler
return result
}
/// Проставляем непроставленного ранее обработчика переходов
mutating func setAnimatingTargetTransitionsHandler(_ transitionsHandler: AnimatingTransitionsHandler)
{
marshrouteAssert(needsAnimatingTargetTransitionHandler)
targetTransitionsHandlerBox = .init(animatingTransitionsHandler: transitionsHandler)
}
}
| mit | 57a98f15a7fbceeb075f0c144caab02b | 43.712871 | 122 | 0.732876 | 6.710253 | false | false | false | false |
swimmath27/GameOfGames | GameOfGames/ViewControllers/DrawCardViewController.swift | 1 | 4593 | //
// DrawCardViewController.swift
// GameOfGames
//
// Created by Michael Lombardo on 5/31/16.
// Copyright © 2016 Michael Lombardo. All rights reserved.
//
import UIKit
class DrawCardViewController: UIViewController {
@IBOutlet weak var playerIntroductionLabel: UILabel!
@IBOutlet weak var youDrewLabel: UILabel!
@IBOutlet weak var cardImageButton: UIButton!
@IBOutlet weak var whichCardLabel: UILabel!
@IBOutlet weak var skipButton: UIButton!
@IBOutlet weak var wonButton: UIButton!
@IBOutlet weak var lostButton: UIButton!
@IBOutlet weak var stolenButton: UIButton!
fileprivate var game:Game = Game.getInstance();
override func viewDidLoad() {
super.viewDidLoad()
playerIntroductionLabel.text = "\(game.getCurrentPlayerName()),"
self.loadCurrentCard();
//TODO: check if losable and hide the lose button as well
//background gradient
self.view.layer.insertSublayer(UIHelper.getBackgroundGradient(), at: 0)
}
func loadCurrentCard() {
whichCardLabel.text = "\(game.getCurrentCard()!.shortDesc)!";
let cardPic: UIImage? = UIImage(named: game.getCurrentCard()!.getFileName())
if cardPic != nil {
cardImageButton.setImage(cardPic, for: UIControlState())
cardImageButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0)
}
else {
cardImageButton.setTitle(game.getCurrentCard()!.toString(), for: UIControlState())
}
if game.getCurrentCard()!.stealable {
stolenButton.isEnabled = true
stolenButton.alpha = 1.0;
}
else {
stolenButton.isEnabled = false
stolenButton.alpha = 0.5;
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cardInfoButtonPressed(_ sender: AnyObject) {
CardInfoViewController.currentCard = game.getCurrentCard()!;
CardInfoViewController.from = "DrawCard";
performSegue(withIdentifier: "DrawCardToCardInfo", sender: nil)
}
@IBAction func WonButtonPressed(_ sender: AnyObject) {
// let drink:String = game.getCurrentCard()!.getDrink();
//alertAndGoBack("Congratz", s:"Please add \(drink) into the cup and send \(drink) to any player on the other team", whichAction: "won")
self.goToNext("won");
}
@IBAction func LostButtonPressed(_ sender: AnyObject) {
// let drink:String = game.getCurrentCard()!.getDrink();
//alertAndGoBack("Too bad", s:"Please drink \(drink) and give \(drink) to a team member",whichAction: "lost")
self.goToNext("lost");
}
@IBAction func StolenButtonPressed(_ sender: AnyObject) {
// let drink:String = game.getCurrentCard()!.getDrink();
//alertAndGoBack("...", s:"Please add \(drink) into the cup and the other team sends \(drink) to any player on your team", whichAction: "stolen")
self.goToNext("stolen");
}
@IBAction func skipCardButtonPressed(_ sender: AnyObject) {
alertAndGoBack("Alert", s:"Card will be skipped. Make sure both team captains agree as this cannot be undone",whichAction: "skipped")
}
/*
// 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.
}
*/
func goToNext(_ whichAction:String) {
switch whichAction {
case "won":
game.cardWasWon();
case "lost":
game.cardWasLost();
case "stolen":
game.cardWasStolen();
case "skipped":
_ = game.drawCard();
self.loadCurrentCard();
return; // stay here if skipped
default: break
}
self.performSegue(
withIdentifier: "DrawCardToPlayGame", sender: self)
}
func alertAndGoBack(_ t:String, s : String, whichAction:String) {
let popup = UIAlertController(title: t,
message: s,
preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title:"OK", style: .default, handler: {
action in self.goToNext(whichAction)
})
popup.addAction(okAction)
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel, handler: nil)
popup.addAction(cancelAction);
self.present(popup, animated: true,
completion: nil)
}
}
| mit | 5ecef711d9d1a2dd54ed2f2d864d7598 | 29.013072 | 149 | 0.66115 | 4.398467 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/WhistlesVsZombies/Node/MOptionWhistlesVsZombiesHud.swift | 1 | 1032 | import Foundation
class MOptionWhistlesVsZombiesHud:MGameUpdate<MOptionWhistlesVsZombies>
{
weak var model:MOptionWhistlesVsZombies!
weak var view:VOptionWhistlesVsZombiesHud?
private var lastElapsedTime:TimeInterval?
private let kUpdateRate:TimeInterval = 0.3
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
if let lastElapsedTime:TimeInterval = self.lastElapsedTime
{
let deltaTime:TimeInterval = abs(elapsedTime - lastElapsedTime)
if deltaTime > kUpdateRate
{
self.lastElapsedTime = elapsedTime
updateView()
}
}
else
{
lastElapsedTime = elapsedTime
}
}
//MARK: private
private func updateView()
{
let zombies:String = "\(model.score)"
let coins:String = "\(model.coins)"
view?.update(zombies:zombies, coins:coins)
}
}
| mit | 6f3d92d7afd04493a97f95250ee56bcf | 25.461538 | 75 | 0.604651 | 5.375 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCFetchedCollection.swift | 2 | 1361 | //
// NCFetchedCollection.swift
// Neocom
//
// Created by Artem Shimanski on 30.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import Foundation
import CoreData
public class NCFetchedCollection<Element : NSFetchRequestResult> {
public let entityName: String
public let predicateFormat: String
public let argumentArray:[Any]
public let managedObjectContext: NSManagedObjectContext
public let request: NSFetchRequest<Element>
public init(entityName: String, predicateFormat: String, argumentArray:[Any], managedObjectContext: NSManagedObjectContext) {
self.entityName = entityName
self.predicateFormat = predicateFormat
self.argumentArray = argumentArray
self.managedObjectContext = managedObjectContext
self.request = NSFetchRequest<Element>(entityName: entityName)
}
public subscript(index: Int) -> Element? {
var argumentArray = self.argumentArray
argumentArray.append(index)
request.predicate = NSPredicate(format: self.predicateFormat, argumentArray: argumentArray)
return (try? managedObjectContext.fetch(request))?.last
}
public subscript(key: String) -> Element? {
var argumentArray = self.argumentArray
argumentArray.append(key)
request.predicate = NSPredicate(format: self.predicateFormat, argumentArray: argumentArray)
return (try? managedObjectContext.fetch(request))?.last
}
}
| lgpl-2.1 | de6fefe00e7ff89c5e55145d7d9d167b | 32.170732 | 126 | 0.785294 | 4.459016 | false | false | false | false |
welbesw/easypost-swift | Example/EasyPostApi/RatesViewController.swift | 1 | 3627 | //
// RatesViewController.swift
// EasyPostApi
//
// Created by William Welbes on 10/6/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import EasyPostApi
class RatesViewController: UITableViewController {
var shipment:EasyPostShipment!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTapCancelButton(_ sender:AnyObject?) {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return the number of rows
return shipment.rates.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "rateCell", for: indexPath) as! RateCell
// Configure the cell...
let rate = self.shipment.rates[(indexPath as NSIndexPath).row]
cell.carrierLabel.text = rate.carrier
cell.serviceLabel.text = rate.service
cell.rateLabel.text = rate.rate
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//Buy the postage that has been selected
let rate = self.shipment.rates[(indexPath as NSIndexPath).row]
if let rateId = rate.id {
let alertController = UIAlertController(title: "Buy Postage", message: "Do you want to buy this postage for \(rate.rate!)", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "Buy", style: UIAlertAction.Style.default, handler: { (action) -> Void in
EasyPostApi.sharedInstance.buyShipment(self.shipment.id!, rateId: rateId, completion: { (result) -> () in
//Handle results
DispatchQueue.main.async(execute: { () -> Void in
if(result.isSuccess) {
print("Successfully bought shipment.")
if let buyResponse = result.value {
if let postageLabel = buyResponse.postageLabel {
if let labelUrl = postageLabel.labelUrl {
print("Label url: \(labelUrl)")
}
}
}
self.dismiss(animated: true, completion: nil)
} else {
print("Error buying shipment: \(result.error?.localizedDescription ?? "")")
}
})
})
}))
self.present(alertController, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 5f5add2882624ef1ffd5e007eb8415a1 | 36.381443 | 182 | 0.586597 | 5.355982 | false | false | false | false |
WeltN24/PiedPiper | Tests/PiedPiperTests/Future+ReduceTests.swift | 1 | 5998 | import Quick
import Nimble
import PiedPiper
extension MutableCollection where Self.Index == Int {
mutating func shuffle() -> Self {
if count < 2 { return self }
for i in startIndex ..< endIndex - 1 {
let j = Int.random(in: 0..<endIndex - i) + i
if i != j {
self.swapAt(i, j)
}
}
return self
}
}
class FutureSequenceReduceTests: QuickSpec {
override func spec() {
describe("Reducing a list of Futures") {
var promises: [Promise<Int>]!
var reducedFuture: Future<Int>!
var successValue: Int?
var failureValue: Error?
var wasCanceled: Bool!
var originalPromisesCanceled: [Bool]!
beforeEach {
let numberOfPromises = 5
originalPromisesCanceled = (0..<numberOfPromises).map { _ in
false
}
promises = (0..<numberOfPromises).map { idx in
Promise().onCancel {
originalPromisesCanceled[idx] = true
}
}
wasCanceled = false
successValue = nil
failureValue = nil
reducedFuture = promises
.map { $0.future }
.reduce(5, combine: +)
reducedFuture.onCompletion { result in
switch result {
case .success(let value):
successValue = value
case .error(let error):
failureValue = error
case .cancelled:
wasCanceled = true
}
}
}
context("when one of the original futures fails") {
let expectedError = TestError.anotherError
beforeEach {
promises.first?.succeed(10)
promises[1].fail(expectedError)
}
it("should fail the reduced future") {
expect(failureValue).notTo(beNil())
}
it("should fail with the right error") {
expect(failureValue as? TestError).to(equal(expectedError))
}
it("should not cancel the reduced future") {
expect(wasCanceled).to(beFalse())
}
it("should not succeed the reduced future") {
expect(successValue).to(beNil())
}
}
context("when one of the original futures is canceled") {
beforeEach {
promises.first?.succeed(10)
promises[1].cancel()
}
it("should not fail the reduced future") {
expect(failureValue).to(beNil())
}
it("should cancel the reduced future") {
expect(wasCanceled).to(beTrue())
}
it("should not succeed the reduced future") {
expect(successValue).to(beNil())
}
}
context("when all the original futures succeed") {
var expectedResult: Int!
context("when they succeed in the same order") {
beforeEach {
expectedResult = 5
promises.enumerated().forEach { (iteration, promise) in
promise.succeed(iteration)
expectedResult = expectedResult + iteration
}
}
it("should not fail the reduced future") {
expect(failureValue).to(beNil())
}
it("should not cancel the reduced future") {
expect(wasCanceled).to(beFalse())
}
it("should succeed the reduced future") {
expect(successValue).notTo(beNil())
}
it("should succeed with the right value") {
expect(successValue).to(equal(expectedResult))
}
}
}
context("when canceling the reduced future") {
context("when no promise was done") {
beforeEach {
reducedFuture.cancel()
}
it("should cancel all the running promises") {
expect(originalPromisesCanceled).to(allPass({ $0 == true}))
}
}
context("when some promise was done") {
let nonRunningPromiseIndex = 1
beforeEach {
promises[nonRunningPromiseIndex].succeed(10)
reducedFuture.cancel()
}
it("should cancel only the non running promises") {
expect(originalPromisesCanceled.filter({ $0 == true }).count).to(equal(promises.count - 1))
}
it("should not cancel the non running promises") {
expect(originalPromisesCanceled[nonRunningPromiseIndex]).to(beFalse())
}
}
}
}
describe("Reducing a list of Futures, independently of the order they succeed") {
var promises: [Promise<String>]!
var reducedFuture: Future<String>!
var successValue: String?
var expectedResult: String!
beforeEach {
promises = [
Promise(),
Promise(),
Promise(),
Promise(),
Promise()
]
successValue = nil
reducedFuture = promises
.map { $0.future }
.reduce("BEGIN-", combine: +)
reducedFuture.onSuccess {
successValue = $0
}
let sequenceOfIndexes = Array(0..<promises.count).map({ "\($0)" }).joined(separator: "")
expectedResult = "BEGIN-\(sequenceOfIndexes)"
var arrayOfIndexes = Array(promises.enumerated())
repeat {
arrayOfIndexes = arrayOfIndexes.shuffle()
} while arrayOfIndexes.map({ $0.0 }) == Array(0..<promises.count)
arrayOfIndexes.forEach { (originalIndex, promise) in
promise.succeed("\(originalIndex)")
}
}
it("should succeed the reduced future") {
expect(successValue).notTo(beNil())
}
it("should succeed with the right value") {
expect(successValue).to(equal(expectedResult))
}
}
}
}
| mit | ec10a2537367f547269de3867827905a | 27.159624 | 103 | 0.526009 | 5.211121 | false | false | false | false |
CocoaheadsSaar/Treffen | Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/MainStackView.swift | 1 | 1722 | //
// MainStackView.swift
// AutolayoutTests
//
// Created by Markus Schmitt on 13.01.16.
// Copyright © 2016 Insecom - Markus Schmitt. All rights reserved.
//
import UIKit
class MainStackView: UIView {
var textLabel: UILabel
var textField: UITextField
var textStackView: UIStackView
override init(frame: CGRect) {
// views
textLabel = UILabel(frame: .zero)
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.text = "Testlabel"
let textSize = textLabel.intrinsicContentSize().width
textField = UITextField(frame: .zero)
textField.borderStyle = .Line
textField.translatesAutoresizingMaskIntoConstraints = false
textStackView = UIStackView(arrangedSubviews: [textLabel, textField])
textStackView.translatesAutoresizingMaskIntoConstraints = false
textStackView.axis = .Horizontal
textStackView.spacing = 10
textStackView.distribution = .Fill
super.init(frame: frame)
backgroundColor = .whiteColor()
addSubview(textStackView)
let views = ["textStackView" : textStackView]
var layoutConstraints = [NSLayoutConstraint]()
layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textStackView]-|", options: [], metrics: nil, views: views)
layoutConstraints.append(textLabel.widthAnchor.constraintEqualToConstant(textSize))
NSLayoutConstraint.activateConstraints(layoutConstraints)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 193f8ab717e3fcb0d2be4ef62eaee13a | 30.290909 | 141 | 0.661825 | 5.736667 | false | false | false | false |
yarrcc/Phonograph | Phonograph/PhonographOutputQueue.swift | 1 | 3581 | import AudioToolbox
import Foundation
public typealias PhonographOutputQueueCallback = (bufferSizeMax: Int) -> NSData
public class PhonographOutputQueue {
class PhonographOutputQueueUserData {
let callback: PhonographOutputQueueCallback
let bufferStub: NSData
init(callback: PhonographOutputQueueCallback, bufferStub: NSData) {
self.callback = callback
self.bufferStub = bufferStub
}
}
private var audioQueueRef: AudioQueueRef = nil
private let userData: PhonographOutputQueueUserData
public init(var asbd: AudioStreamBasicDescription, callback: PhonographOutputQueueCallback, buffersCount: UInt32 = 3, bufferSize: UInt32 = 9600) throws {
// TODO: Try to remove unwrap.
self.userData = PhonographOutputQueueUserData(callback: callback, bufferStub: NSMutableData(length: Int(bufferSize))!)
let userDataUnsafe = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self.userData).toOpaque())
let code = AudioQueueNewOutput(&asbd, audioQueueOutputCallback, userDataUnsafe, nil, nil, 0, &audioQueueRef)
if code != noErr {
throw PhonographError.GenericError(code)
}
for _ in 0..<buffersCount {
var bufferRef = AudioQueueBufferRef()
let code = AudioQueueAllocateBuffer(audioQueueRef, bufferSize, &bufferRef)
if code != noErr {
throw PhonographError.GenericError(code)
}
audioQueueOutputCallback(userDataUnsafe, audioQueueRef, bufferRef)
}
}
deinit {
do {
try dispose()
} catch {
// TODO: Probably handle this exception.
}
}
public func dispose() throws {
let code = AudioQueueDispose(audioQueueRef, true)
if code != noErr {
throw PhonographError.GenericError(code)
}
audioQueueRef = nil
}
public func start() throws {
let code = AudioQueueStart(audioQueueRef, nil)
if code != noErr {
throw PhonographError.GenericError(code)
}
}
public func stop() throws {
let code = AudioQueueStop(audioQueueRef, true)
if code != noErr {
throw PhonographError.GenericError(code)
}
}
private let audioQueueOutputCallback: AudioQueueOutputCallback = { (inUserData, inAQ, inBuffer) in
let userData = Unmanaged<PhonographOutputQueueUserData>.fromOpaque(COpaquePointer(inUserData)).takeUnretainedValue()
// TODO: Think about cast.
let capacity = Int(inBuffer.memory.mAudioDataBytesCapacity)
let dataFromCallback = userData.callback(bufferSizeMax: capacity)
// Audio queue will stop requesting buffers if output buffer will not contain bytes.
// Use empty buffer filled with zeroes.
let data = dataFromCallback.length > 0 ? dataFromCallback : userData.bufferStub
let dataInputRaw = UnsafeMutablePointer<Int8>(data.bytes)
let dataOutputRaw = UnsafeMutablePointer<Int8>(inBuffer.memory.mAudioData)
dataOutputRaw.assignFrom(dataInputRaw, count: data.length)
// TODO: Think about cast.
inBuffer.memory.mAudioDataByteSize = UInt32(data.length)
// TODO: Handle error.
AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, nil)
}
} | mit | 4c0e078bd064c950246361ab4500017e | 32.792453 | 157 | 0.625803 | 5.159942 | false | false | false | false |
alblue/swift | test/SILGen/c_function_pointers.swift | 2 | 2775 | // RUN: %target-swift-emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden @$s19c_function_pointers6valuesyS2iXCS2iXCF
// CHECK: bb0(%0 : @trivial $@convention(c) (Int) -> Int):
// CHECK: return %0 : $@convention(c) (Int) -> Int
@discardableResult
func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int {
return arg(x)
}
// CHECK-LABEL: sil hidden @$s19c_function_pointers5callsyS3iXC_SitF
// CHECK: bb0(%0 : @trivial $@convention(c) @noescape (Int) -> Int, %1 : @trivial $Int):
// CHECK: [[RESULT:%.*]] = apply %0(%1)
// CHECK: return [[RESULT]]
@discardableResult
func calls_no_args(_ arg: @convention(c) () -> Int) -> Int {
return arg()
}
func global(_ x: Int) -> Int { return x }
func no_args() -> Int { return 42 }
// CHECK-LABEL: sil hidden @$s19c_function_pointers0B19_to_swift_functionsyySiF
func pointers_to_swift_functions(_ x: Int) {
// CHECK: bb0([[X:%.*]] : @trivial $Int):
func local(_ y: Int) -> Int { return y }
// CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo
// CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls(global, x)
// CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo
// CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls(local, x)
// CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To
// CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls({ $0 + 1 }, x)
calls_no_args(no_args)
// CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo
// CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]]
// CHECK: apply {{.*}}([[CVT]])
}
func unsupported(_ a: Any) -> Int { return 0 }
func pointers_to_bad_swift_functions(_ x: Int) {
calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}}
}
// CHECK-LABEL: sil private @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () {
// CHECK-LABEL: sil private [thunk] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () {
struct StructWithInitializers {
let fn1: @convention(c) () -> () = {}
init(a: ()) {}
init(b: ()) {}
}
func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{
func foo(y: Int) -> Int { return y }
return calls(foo, 0)
}
| apache-2.0 | a60b37d0b0ecc1608d41baa947437e23 | 36 | 155 | 0.611532 | 3.049451 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBButton.swift | 1 | 13304 | // =============================================================================
// PHOTTY
// Copyright (C) 2015 NeroBlu. All rights reserved.
// =============================================================================
import UIKit
public enum NBButtonLayout {
case None
case VerticalImageText(interval:CGFloat)
case LeftAlign(edge:CGFloat, interval:CGFloat)
}
// MARK: - NBButton -
/// カスタムなボタンクラス
///
/// このボタンクラスは以下の機能があります
/// * ハイライト背景色・文字色(highlightedBackgroundColor: XIBから設定可能)
/// * 枠線のみのボタン(linedFrame: XIBから設定可能)
/// * 角丸(cornerRadius: XIBから設定可能)
@IBDesignable public class NBButton : UIButton {
private var originalBackgroundColor: UIColor?
private var originalBorderColor: UIColor?
// MARK: 角丸
/// 角丸の半径
@IBInspectable public var cornerRadius : Float = 0.0 {
didSet { let v = self.cornerRadius
self.layer.cornerRadius = CGFloat(v)
}
}
// MARK: 枠線
/// 枠線の太さ
@IBInspectable public var borderWidth : Float = 0.0 {
didSet { let v = self.borderWidth
self.layer.borderWidth = CGFloat(v)
}
}
/// 枠線の色
@IBInspectable public var borderColor : UIColor? {
didSet { let v = self.borderColor
self.originalBorderColor = v
self.layer.borderColor = v?.CGColor
}
}
// MARK: ハイライト
/// 通常文字色
@IBInspectable public var normalTitleColor : UIColor? = nil {
didSet { let v = self.normalTitleColor
self.setTitleColor(v, forState: .Normal)
}
}
/// 通常背景色
/// setTitleColor(_:forState:)を使用せずに設定できる
@IBInspectable public var normalBackgroundColor : UIColor? = nil {
didSet { let v = self.normalBackgroundColor
self.originalBackgroundColor = v
self.backgroundColor = v
}
}
/// ハイライト時の文字色
@IBInspectable public var highlightedTitleColor : UIColor? = nil {
didSet { let v = self.highlightedTitleColor
self.setTitleColor(v, forState: .Highlighted)
}
}
/// ハイライト時の背景色
@IBInspectable public var highlightedBackgroundColor : UIColor? = nil
/// ハイライト時の枠線の色
@IBInspectable public var highlightedBorderColor : UIColor?
override public var highlighted: Bool {
get {
return super.highlighted
}
set(v) {
super.highlighted = v
let nb = self.originalBackgroundColor, hb = self.highlightedBackgroundColor, cb = v ? hb : nb
self.backgroundColor = cb
let nl = self.originalBorderColor, hl = self.highlightedBorderColor, cl = v ? hl : nl
self.layer.borderColor = cl?.CGColor
}
}
// MARK: 定形レイアウト
/// 定形レイアウト種別
public var fixedLayout: NBButtonLayout = .None {
didSet {
self.applyFixedLayout()
}
}
override public var frame: CGRect {
didSet {
self.applyFixedLayout()
}
}
private struct SizeSet {
var bw: CGFloat = 0 // buttonWidth
var bh: CGFloat = 0 // buttonHeight
var iw: CGFloat = 0 // imageWidth
var ih: CGFloat = 0 // imageHeight
var tw: CGFloat = 0 // textWidth
var th: CGFloat = 0 // textHeight
init?(button: UIButton) {
guard let imageView = button.imageView, let titleLabel = button.titleLabel else {
return nil
}
self.bw = crW(button.bounds)
self.bh = crH(button.bounds)
self.iw = crW(imageView.bounds)
self.ih = crH(imageView.bounds)
self.tw = crW(titleLabel.bounds)
self.th = crH(titleLabel.bounds)
}
}
public func applyFixedLayout() {
guard let size = SizeSet(button: self) else {
return
}
switch self.fixedLayout {
case .VerticalImageText: self.updateEdgeInsetsVerticalImageText(size)
case .LeftAlign: self.updateEdgeInsetsLeftAlign(size)
default:break
}
}
private func updateEdgeInsetsVerticalImageText(s: SizeSet) {
var interval:CGFloat = 0
switch self.fixedLayout {
case .VerticalImageText(let i): interval = i
default:return // dead code
}
let verticalMergin = (s.bh - (s.th + interval + s.ih)) / 2.0
let imageHorizonMergin = (s.bw - s.iw) / 2.0
// content
var t:CGFloat = 0, l:CGFloat = 0, b:CGFloat = 0, r:CGFloat = 0
self.contentEdgeInsets = UIEdgeInsetsMake(t, l, b, r)
// image
t = verticalMergin
l = imageHorizonMergin
b = verticalMergin + s.th + (interval / 2.0)
r = imageHorizonMergin - s.tw
self.imageEdgeInsets = UIEdgeInsetsMake(t, l, b, r)
// text
t = verticalMergin + s.ih + (interval / 2.0)
l = -s.iw
b = verticalMergin
r = 0
self.titleEdgeInsets = UIEdgeInsetsMake(t, l, b, r)
}
private func updateEdgeInsetsLeftAlign(s: SizeSet) {
var edge:CGFloat = 0, interval:CGFloat = 0, l:CGFloat = 0
switch self.fixedLayout {
case .LeftAlign(let e, let i): edge = e; interval = i
default:return // dead code
}
// content
l = s.bw - s.tw - s.iw - edge
self.contentEdgeInsets = UIEdgeInsetsMake(0, -l, 0, 0)
// text
l = interval
self.titleEdgeInsets = UIEdgeInsetsMake(0, l, 0, 0)
}
// MARK: 初期化
/// インスタン生成時の共通処理
internal func commonInitialize() {
self.originalBackgroundColor = self.backgroundColor
}
override public init (frame : CGRect) { super.init(frame : frame); commonInitialize() }
convenience public init () { self.init(frame:CGRect.zero) }
required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); commonInitialize() }
}
// MARK: - UIButton Extension -
public extension UIButton {
/// タイトルラベルのフォント
public var titleFont: UIFont? {
get {
return self.titleLabel?.font
}
set(v) {
guard let titleLabel = self.titleLabel else { return }
titleLabel.font = v
}
}
}
// MARK: - NBLongPressableButton -
/// NBLongPressableButton用デリゲートプロトコル
@objc public protocol NBLongPressableButtonDelegate {
/// 継続的な長押しイベントが発生した時(押しっぱなし中に一定間隔で呼ばれる)
/// - parameter longPressableButton: ボタンの参照
/// - parameter times: イベント発生回数(1から始まる通し番号)
optional func longPressableButtonDidHoldPress(longPressableButton: NBLongPressableButton, times: UInt64)
/// 継続的な長押しが始まった時
/// - parameter longPressableButton: ボタンの参照
optional func longPressableButtonDidStartLongPress(longPressableButton: NBLongPressableButton)
/// 継続的な長押しが終わった時
/// - parameter longPressableButton: ボタンの参照
optional func longPressableButtonDidStopLongPress(longPressableButton: NBLongPressableButton)
}
/// 継続的長押しが可能なボタンクラス
@IBDesignable public class NBLongPressableButton : NBButton {
/// デリゲート
@IBOutlet public weak var delegate: NBLongPressableButtonDelegate?
/// 長押しを感知するまでに要する秒数
@IBInspectable public var longPressRecognizeDuration : Double = 1.2 // as CFTimeInterval
/// 1段階目の長押し継続を感知するまでに要する秒数
@IBInspectable public var primaryIntervalOfContinuousEvent : Double = 0.1
/// 1段階目の長押し継続を繰り返す回数
@IBInspectable public var primaryTimesOfContinuousEvent : Int = 10
/// 2段階目の長押し継続を感知するまでに要する秒数
@IBInspectable public var secondaryIntervalOfContinuousEvent : Double = 0.05
/// 2段階目の長押し継続を繰り返す回数
@IBInspectable public var secondaryTimesOfContinuousEvent : Int = 50
/// 3段階目の長押し継続を感知するまでに要する秒数
@IBInspectable public var finalyIntervalOfContinuousEvent : Double = 0.01
enum ContinuousEventPhase { case Primary, Secondary, Finaly }
private let longPressMinimumPressDuration: Double = 1.0
private var longPressRecognizer: UILongPressGestureRecognizer?
private var longPressTimer: NSTimer?
private var touchesStarted: CFTimeInterval?
private var touchesEnded: Bool = false
private var eventPhase: ContinuousEventPhase = .Primary
private var eventTimes: Int = 0
private var eventTotalTimes: UInt64 = 0
internal override func commonInitialize() {
super.commonInitialize()
let lpr = UILongPressGestureRecognizer(target: self, action: Selector("didRecognizeLongPress:"))
lpr.cancelsTouchesInView = false
lpr.minimumPressDuration = self.longPressRecognizeDuration
self.addGestureRecognizer(lpr)
}
@objc private func didRecognizeLongPress(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .Began {
self.didBeginPressButton()
} else if recognizer.state == .Ended {
self.didEndPressButton()
}
}
private func didBeginPressButton() {
if self.touchesStarted != nil { return }
self.setNeedsDisplay()
self.touchesStarted = CACurrentMediaTime()
self.touchesEnded = false
let delta = Int64(Double(NSEC_PER_SEC) * self.longPressMinimumPressDuration)
let delay = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_after(delay, dispatch_get_main_queue()) { [weak self] in
if let strongSelf = self where strongSelf.touchesEnded {
strongSelf.didEndPressButton()
}
}
self.delegate?.longPressableButtonDidStartLongPress?(self)
self.startLongPressTimer()
}
private func didEndPressButton() {
if let touchesStarted = self.touchesStarted where (CACurrentMediaTime() - touchesStarted) >= Double(self.longPressMinimumPressDuration) {
self.touchesStarted = nil
self.stopLongPressTimer()
self.delegate?.longPressableButtonDidStopLongPress?(self)
}
else {
self.touchesEnded = true
}
}
private func startLongPressTimer() {
self.eventPhase = .Primary
self.eventTimes = 0
self.eventTotalTimes = 0
self.longPressTimer = NSTimer.scheduledTimerWithTimeInterval(self.intervalOfContinuousEvent,
target: self,
selector: Selector("didFireLongPressTimer:"),
userInfo: nil,
repeats: false
)
}
@objc private func didFireLongPressTimer(timer: NSTimer) {
if self.eventTotalTimes < UINT64_MAX {
self.eventTotalTimes++
}
self.delegate?.longPressableButtonDidHoldPress?(self, times: self.eventTotalTimes)
if self.eventPhase != .Finaly && ++self.eventTimes >= self.timesOfContinuousEvent {
self.updateToNextContinuousEventPhase()
self.eventTimes = 0
}
self.longPressTimer = NSTimer.scheduledTimerWithTimeInterval(self.intervalOfContinuousEvent,
target: self,
selector: Selector("didFireLongPressTimer:"),
userInfo: nil,
repeats: false
)
}
private func stopLongPressTimer() {
if let timer = self.longPressTimer where timer.valid {
timer.invalidate()
}
self.longPressTimer = nil
}
private var intervalOfContinuousEvent: NSTimeInterval {
switch self.eventPhase {
case .Primary: return self.primaryIntervalOfContinuousEvent
case .Secondary: return self.secondaryIntervalOfContinuousEvent
case .Finaly: return self.finalyIntervalOfContinuousEvent
}
}
private var timesOfContinuousEvent: Int {
switch self.eventPhase {
case .Primary: return self.primaryTimesOfContinuousEvent
case .Secondary: return self.secondaryTimesOfContinuousEvent
case .Finaly: return -1
}
}
private func updateToNextContinuousEventPhase() {
if self.eventPhase == .Primary {
self.eventPhase = .Secondary
} else if self.eventPhase == .Secondary {
self.eventPhase = .Finaly
}
}
}
| apache-2.0 | 015e003201e21a12a232a114a7656e28 | 31.661417 | 145 | 0.604789 | 4.325339 | false | false | false | false |
Tanner1638/SAD_Final | CuppitProject/Cuppit/GameScene.swift | 1 | 17535 | //
// GameScene.swift
// Cuppit
//
// Created by Austin Sands on 11/5/16.
// Copyright © 2016 Austin Sands. All rights reserved.
//
import SpriteKit
struct PhysicsCatagory {
static let enemyCatagory : UInt32 = 0x1 << 0
static let cupCategory : UInt32 = 0x1 << 1
static let scoreCategory: UInt32 = 0x1 << 2
}
//create score and highscore variables
var score = 0
var highScore = 0
class GameScene: SKScene, SKPhysicsContactDelegate {
var rotatorValue: Float = 0
var EnemyTimer = Timer()
var gameStarted = false
var cup: SKSpriteNode!
var scoreNode = SKSpriteNode()
var ScoreLbl = SKLabelNode(fontNamed: "Gameplay")
var HighScoreLbl = SKLabelNode(fontNamed: "Gameplay")
var slider: UISlider!
var lastTouch: CGPoint? = nil
var ableToPlay = true
var pausePlayBTN: SKSpriteNode!
var nodeSpeed = 12.0
var timeDuration = 0.8
let pauseTexture = SKTexture(imageNamed: "Pause Filled-50")
let playTexture = SKTexture(imageNamed: "Play Filled-50")
let homeTexture = SKTexture(imageNamed: "Home-48")
var homeBtn: SKSpriteNode!
override func didMove(to view: SKView) {
//stuff to setup scene
SceneSetup()
Cup()
Scores()
ScoreNode()
PausePlayButton()
HomeBtn()
}
func SceneSetup(){
score = 0
self.physicsWorld.contactDelegate = self
self.anchorPoint = CGPoint(x: 0, y: 0)
//self.backgroundColor = UIColor(red: 0.1373, green: 0.1373, blue: 0.1373, alpha: 1.0)
self.backgroundColor = UIColor.black
self.isPaused = false
let starBackground = SKEmitterNode(fileNamed: "StarBackground")!
starBackground.particlePositionRange.dx = self.frame.size.width
starBackground.particlePositionRange.dy = self.frame.size.height
starBackground.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
starBackground.zPosition = 0.5
self.addChild(starBackground)
}
func Cup(){
//create the cup
let cupTexture = SKTexture(imageNamed: "CuppitC")
cup = SKSpriteNode(texture: cupTexture)
cup.size = CGSize(width: 180, height: 180)
cup.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
cup.physicsBody = SKPhysicsBody(texture: cupTexture, size: CGSize(width: cup.size.width, height: cup.size.height))
cup.physicsBody?.affectedByGravity = false
cup.physicsBody?.isDynamic = false
cup.physicsBody?.allowsRotation = true
cup.physicsBody?.categoryBitMask = PhysicsCatagory.cupCategory
cup.physicsBody?.contactTestBitMask = PhysicsCatagory.enemyCatagory
cup.physicsBody?.collisionBitMask = PhysicsCatagory.enemyCatagory
cup.zRotation = CGFloat(rotatorValue)
cup.name = "cup"
cup.zPosition = 5
cup.setScale(1.0)
self.addChild(cup)
cup.run(pulseAnimation())
cup.physicsBody?.usesPreciseCollisionDetection = true
cup.physicsBody?.restitution = 1.0
}
func Scores(){
//save highscore
let HighscoreDefault = UserDefaults.standard
if HighscoreDefault.value(forKey: "Highscore") != nil {
highScore = HighscoreDefault.value(forKey: "Highscore") as! Int
HighScoreLbl.text = "\(highScore)"
}
HighScoreLbl.fontSize = 60
HighScoreLbl.position = CGPoint(x: self.frame.size.width - 15, y: self.frame.height - 15)
HighScoreLbl.fontColor = SKColor(red: 1, green: 0.9804, blue: 0, alpha: 1.0)
HighScoreLbl.text = "\(highScore)"
HighScoreLbl.zPosition = 5
HighScoreLbl.horizontalAlignmentMode = .right
HighScoreLbl.verticalAlignmentMode = .top
self.addChild(HighScoreLbl)
ScoreLbl.fontSize = 110
ScoreLbl.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.height - ((self.frame.height - cup.position.y) / 2))
ScoreLbl.fontColor = SKColor(red: 0, green: 0.4784, blue: 0.9294, alpha: 1.0)
ScoreLbl.text = "\(score)"
ScoreLbl.horizontalAlignmentMode = .center
ScoreLbl.verticalAlignmentMode = .center
ScoreLbl.zPosition = 5
self.addChild(ScoreLbl)
}
func ScoreNode(){
scoreNode.size = CGSize(width: 10, height: 10)
scoreNode.color = SKColor.clear
scoreNode.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
scoreNode.name = "scoreNode"
scoreNode.physicsBody = SKPhysicsBody(rectangleOf: scoreNode.size)
scoreNode.physicsBody?.affectedByGravity = false
scoreNode.physicsBody?.isDynamic = false
scoreNode.physicsBody?.allowsRotation = false
scoreNode.physicsBody?.categoryBitMask = PhysicsCatagory.scoreCategory
scoreNode.physicsBody?.contactTestBitMask = PhysicsCatagory.enemyCatagory
scoreNode.physicsBody?.collisionBitMask = PhysicsCatagory.enemyCatagory
scoreNode.zPosition = 1
self.addChild(scoreNode)
}
func PausePlayButton(){
pausePlayBTN = SKSpriteNode(texture: pauseTexture)
pausePlayBTN.size = CGSize(width: 60, height: 60)
pausePlayBTN.anchorPoint = CGPoint(x: 0.0, y: 1.0)
pausePlayBTN.position = CGPoint(x: 10, y: self.frame.height - 10)
pausePlayBTN.name = "Pause"
pausePlayBTN.zPosition = 5
self.addChild(pausePlayBTN)
}
func HomeBtn() {
homeBtn = SKSpriteNode(texture: homeTexture)
homeBtn.size = CGSize(width: 60, height: 60)
homeBtn.anchorPoint = CGPoint(x: 0.0, y: 1.0)
homeBtn.position = CGPoint(x: pausePlayBTN.position.x + 60, y: self.frame.height - 10)
homeBtn.name = "Home"
homeBtn.zPosition = 5
self.addChild(homeBtn)
}
func GameOver(){
scoreNode.removeFromParent()
self.removeAllActions()
EnemyTimer.invalidate()
gameStarted = false
cup.removeAllActions()
self.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.run {
let GameOverScene = GameScene(fileNamed: "GameOverScene")
GameOverScene?.scaleMode = .aspectFill
GameOverScene?.size = (self.view?.bounds.size)!
self.view?.presentScene(GameOverScene!, transition: SKTransition.push(with: .up, duration: 0.5))
}]))
}
func pulseAnimation() -> SKAction {
let duration = 1.0
let pulseOut = SKAction.scale(to: 1.2, duration: duration)
let pulseIn = SKAction.scale(to: 1.0, duration: duration)
let pulse = SKAction.sequence([pulseOut, pulseIn])
return SKAction.repeatForever(pulse)
}
func Enemies(){
let Enemy = SKSpriteNode(imageNamed: "EnemyCool")
Enemy.size = CGSize(width: 30, height: 30)
//Physics
Enemy.physicsBody = SKPhysicsBody(circleOfRadius: Enemy.size.width / 2)
Enemy.physicsBody?.categoryBitMask = PhysicsCatagory.enemyCatagory
Enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.cupCategory | PhysicsCatagory.scoreCategory
Enemy.physicsBody?.collisionBitMask = PhysicsCatagory.cupCategory | PhysicsCatagory.scoreCategory
Enemy.physicsBody?.affectedByGravity = false
Enemy.physicsBody?.isDynamic = true
Enemy.zPosition = 1
Enemy.name = "Enemy"
Enemy.physicsBody?.friction = 0
Enemy.physicsBody?.angularDamping = 0
Enemy.physicsBody?.linearDamping = 0
Enemy.physicsBody?.usesPreciseCollisionDetection = true
Enemy.physicsBody?.restitution = 1.0
let trailNode = SKNode()
trailNode.zPosition = 3
addChild(trailNode)
let trail = SKEmitterNode(fileNamed: "TrailForEnemy")!
trail.targetNode = trailNode
Enemy.addChild(trail)
let RandomPosNmbr = arc4random() % 4 //8
switch RandomPosNmbr{
case 0:
Enemy.position.x = -100
let PositionY = arc4random_uniform(UInt32(frame.size.height))
Enemy.position.y = CGFloat(PositionY)
var dx = CGFloat(cup.position.x - Enemy.position.x)
var dy = CGFloat(cup.position.y - Enemy.position.y)
let magnitude = sqrt(dx * dx + dy * dy)
dx /= magnitude
dy /= magnitude
self.addChild(Enemy)
let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy)
Enemy.physicsBody?.applyImpulse(vector)
break
case 1:
Enemy.position.y = -100
let PositionX = arc4random_uniform(UInt32(frame.size.width))
Enemy.position.x = CGFloat(PositionX)
var dx = CGFloat(cup.position.x - Enemy.position.x)
var dy = CGFloat(cup.position.y - Enemy.position.y)
let magnitude = sqrt(dx * dx + dy * dy)
dx /= magnitude
dy /= magnitude
self.addChild(Enemy)
let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy)
Enemy.physicsBody?.applyImpulse(vector)
break
case 2:
Enemy.position.y = frame.size.height + 100
let PositionX = arc4random_uniform(UInt32(frame.size.width))
Enemy.position.x = CGFloat(PositionX)
var dx = CGFloat(cup.position.x - Enemy.position.x)
var dy = CGFloat(cup.position.y - Enemy.position.y)
let magnitude = sqrt(dx * dx + dy * dy)
dx /= magnitude
dy /= magnitude
self.addChild(Enemy)
let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy)
Enemy.physicsBody?.applyImpulse(vector)
break
case 3:
Enemy.position.x = frame.size.width + 100
let PositionY = arc4random_uniform(UInt32(frame.size.height))
Enemy.position.y = CGFloat(PositionY)
var dx = CGFloat(cup.position.x - Enemy.position.x)
var dy = CGFloat(cup.position.y - Enemy.position.y)
let magnitude = sqrt(dx * dx + dy * dy)
dx /= magnitude
dy /= magnitude
self.addChild(Enemy)
let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy)
Enemy.physicsBody?.applyImpulse(vector)
break
default:
break
}
}
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.node != nil && contact.bodyB.node != nil{
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
if ((firstBody.name == "cup") && (secondBody.name == "Enemy")){
collisionMain(secondBody)
}
else if ((firstBody.name == "Enemy") && (secondBody.name == "cup")){
collisionMain(firstBody)
}
else if ((firstBody.name == "scoreNode") && (secondBody.name == "Enemy")){
collisionScore(secondBody)
}
else if ((firstBody.name == "Enemy") && (secondBody.name == "scoreNode")){
collisionScore(firstBody)
}
}
}
func collisionMain(_ Enemy : SKSpriteNode){
func explodeBall(_ node: SKNode) {
let emitter = SKEmitterNode(fileNamed: "ExplodeParticle")!
emitter.position = node.position
emitter.zPosition = 10
addChild(emitter)
emitter.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.removeFromParent()]))
node.removeFromParent()
}
func explodeCup(_ node: SKNode) {
let emitter = SKEmitterNode(fileNamed: "CupExplodeParticle")!
emitter.position = node.position
emitter.zPosition = 10
addChild(emitter)
emitter.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.removeFromParent()]))
node.removeFromParent()
}
explodeCup(cup)
explodeBall(Enemy)
ableToPlay = false
Enemy.removeAllActions()
GameOver()
}
func collisionScore(_ Enemy : SKSpriteNode){
Enemy.removeAllActions()
Enemy.removeFromParent()
if gameStarted {
if score <= 8 {
timeDuration = 1.2
} else {
timeDuration = 0.8
}
nodeSpeed += 0.5
score += 1
ScoreLbl.text = "\(score)"
if score > highScore {
let HighscoreDefault = UserDefaults.standard
highScore = score
HighscoreDefault.set(highScore, forKey: "Highscore")
HighScoreLbl.text = "\(highScore)"
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if gameStarted == false && ableToPlay {
cup.removeAllActions()
cup.run(SKAction.scale(to: 1.0, duration: 0.5))
EnemyTimer = Timer.scheduledTimer(timeInterval: timeDuration, target: self, selector: #selector(GameScene.Enemies), userInfo: nil, repeats: true)
gameStarted = true
}
handleTouches(touches)
for touch in touches {
let location = touch.location(in: self)
let nodes = self.nodes(at: location)
for node in nodes
{
if node.name == "Pause"
{
self.isPaused = true
pausePlayBTN.name = "Play"
pausePlayBTN.texture = playTexture
EnemyTimer.invalidate()
} else if node.name == "Play" {
self.isPaused = false
pausePlayBTN.name = "Pause"
pausePlayBTN.texture = pauseTexture
EnemyTimer = Timer.scheduledTimer(timeInterval: timeDuration, target: self, selector: #selector(GameScene.Enemies), userInfo: nil, repeats: true)
} else if node.name == "Home" {
score = 0
self.removeAllActions()
let MenuScene = GameScene(fileNamed: "MenuScene")
MenuScene?.scaleMode = .aspectFill
MenuScene?.size = (self.view?.bounds.size)!
self.view?.presentScene(MenuScene!, transition: SKTransition.push(with: .up, duration: 0.5))
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouches(touches)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouches(touches)
}
fileprivate func handleTouches(_ touches: Set<UITouch>) {
for touch in touches {
let touchLocation = touch.location(in: self)
lastTouch = touchLocation
}
}
override func didSimulatePhysics() {
if let _ = cup {
updateCup()
}
}
fileprivate func shouldMove(currentPosition: CGPoint, touchPosition: CGPoint) -> Bool {
return abs(currentPosition.x - touchPosition.x) > cup!.frame.width / 2 ||
abs(currentPosition.y - touchPosition.y) > cup!.frame.height / 2
}
func updateCup(){
if let touch = lastTouch {
let currentPosition = cup!.position
if shouldMove(currentPosition: currentPosition, touchPosition: touch) {
let angle = atan2(currentPosition.y - touch.y, currentPosition.x - touch.x) + CGFloat(M_PI)
let rotateAction = SKAction.rotate(toAngle: angle - CGFloat(M_PI*0.5), duration: 0)
cup.run(rotateAction)
}
}
}
}
| mit | c5788a3f4953f68afebe555617214953 | 30.88 | 165 | 0.544713 | 4.893665 | false | false | false | false |
Natoto/arcgis-runtime-samples-ios | AsynchronousGPSample/swift/AsynchronousGP/AsyncGPParameters.swift | 4 | 1705 | // Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
import Foundation
import ArcGIS
class AsyncGPParameters {
var featureSet:AGSFeatureSet?
var windDirection:NSDecimalNumber
var materialType:String
var dayOrNightIncident:String
var largeOrSmallSpill:String
init() {
windDirection = NSDecimalNumber(double: 90)
materialType = "Anhydrous ammonia"
dayOrNightIncident = "Day"
largeOrSmallSpill = "Large"
}
func parametersArray() -> [AGSGPParameterValue] {
//create parameters
var paramLoc = AGSGPParameterValue(name: "Incident_Point", type: .FeatureRecordSetLayer, value: self.featureSet!)
var paramDegree = AGSGPParameterValue(name: "Wind_Bearing__direction_blowing_to__0_-_360_", type: .Double, value: self.windDirection.doubleValue)
var paramMaterial = AGSGPParameterValue(name: "Material_Type", type: .String, value: self.materialType)
var paramTime = AGSGPParameterValue(name: "Day_or_Night_incident", type: .String, value: self.dayOrNightIncident)
var paramType = AGSGPParameterValue(name: "Large_or_Small_spill", type: .String, value: self.largeOrSmallSpill)
var params:[AGSGPParameterValue] = [paramLoc, paramDegree, paramTime, paramType, paramMaterial]
return params
}
} | apache-2.0 | 46fb7e1bb5397c64e35d2e9759428a5d | 40.609756 | 153 | 0.717302 | 4.118357 | false | false | false | false |
sajnabjohn/WebPage | WebPage/Classes/Reachability.swift | 1 | 5538 | //
// Reachability.swift
// Copyright © 2016 . All rights reserved.
//
import Foundation
import SystemConfiguration
public let ReachabilityDidChangeNotificationName = "ReachabilityDidChangeNotification"
enum ReachabilityStatus {
case notReachable
case reachableViaWiFi
case reachableViaWWAN
}
class Reachability: NSObject {
private var networkReachability: SCNetworkReachability?
private var notifying: Bool = false
init?(hostAddress: sockaddr_in) {
var address = hostAddress
guard let defaultRouteReachability = withUnsafePointer(to: &address, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, $0)
}
}) else {
return nil
}
networkReachability = defaultRouteReachability
super.init()
if networkReachability == nil {
return nil
}
}
static func networkReachabilityForInternetConnection() -> Reachability? {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
return Reachability(hostAddress: zeroAddress)
}
static func networkReachabilityForLocalWiFi() -> Reachability? {
var localWifiAddress = sockaddr_in()
localWifiAddress.sin_len = UInt8(MemoryLayout.size(ofValue: localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 (0xA9FE0000).
localWifiAddress.sin_addr.s_addr = 0xA9FE0000
return Reachability(hostAddress: localWifiAddress)
}
func startNotifier() -> Bool {
guard notifying == false else {
return false
}
var context = SCNetworkReachabilityContext()
context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
guard let reachability = networkReachability, SCNetworkReachabilitySetCallback(reachability, { (target: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in
if let currentInfo = info {
let infoObject = Unmanaged<AnyObject>.fromOpaque(currentInfo).takeUnretainedValue()
if infoObject is Reachability {
let networkReachability = infoObject as! Reachability
NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityDidChangeNotificationName), object: networkReachability)
}
}
}, &context) == true else { return false }
guard SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) == true else { return false }
notifying = true
return notifying
}
func stopNotifier() {
if let reachability = networkReachability, notifying == true {
SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue )
notifying = false
}
}
private var flags: SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags(rawValue: 0)
if let reachability = networkReachability, withUnsafeMutablePointer(to: &flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) == true {
return flags
}
else {
return []
}
}
var currentReachabilityStatus: ReachabilityStatus {
if flags.contains(.reachable) == false {
// The target host is not reachable.
return .notReachable
}
else if flags.contains(.isWWAN) == true {
// WWAN connections are OK if the calling application is using the CFNetwork APIs.
return .reachableViaWWAN
}
else if flags.contains(.connectionRequired) == false {
// If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
return .reachableViaWiFi
}
else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
// The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
return .reachableViaWiFi
}
else {
return .notReachable
}
}
var isReachable: Bool {
switch currentReachabilityStatus {
case .notReachable:
return false
case .reachableViaWiFi, .reachableViaWWAN:
return true
}
}
deinit {
stopNotifier()
}
}
| mit | a80e00ae47202a1c19398251557867da | 38.834532 | 208 | 0.580459 | 6.438372 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/EditHomepageViewController.swift | 1 | 1716 | import Foundation
class EditHomepageViewController: GutenbergViewController {
required init(
post: AbstractPost,
loadAutosaveRevision: Bool = false,
replaceEditor: @escaping ReplaceEditorCallback,
editorSession: PostEditorAnalyticsSession? = nil,
navigationBarManager: PostEditorNavigationBarManager? = nil
) {
let navigationBarManager = navigationBarManager ?? HomepageEditorNavigationBarManager()
super.init(post: post, loadAutosaveRevision: loadAutosaveRevision, replaceEditor: replaceEditor, editorSession: editorSession, navigationBarManager: navigationBarManager)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private(set) lazy var homepageEditorStateContext: PostEditorStateContext = {
return PostEditorStateContext(post: post, delegate: self, action: .continueFromHomepageEditing)
}()
override var postEditorStateContext: PostEditorStateContext {
return homepageEditorStateContext
}
// If there are changes, offer to save them, otherwise continue will dismiss the editor with no changes.
override func continueFromHomepageEditing() {
if editorHasChanges {
handlePublishButtonTap()
} else {
cancelEditing()
}
}
}
extension EditHomepageViewController: HomepageEditorNavigationBarManagerDelegate {
var continueButtonText: String {
return postEditorStateContext.publishButtonText
}
func navigationBarManager(_ manager: HomepageEditorNavigationBarManager, continueWasPressed sender: UIButton) {
requestHTML(for: .continueFromHomepageEditing)
}
}
| gpl-2.0 | 90c0f491005340adc0896a1f6d77c024 | 37.133333 | 178 | 0.734266 | 5.62623 | false | false | false | false |
JQHee/JQProgressHUD | Source/JQWeakTimerObject.swift | 2 | 1415 | //
// test.swift
// JQProgressHUD
//
// Created by HJQ on 2017/7/2.
// Copyright © 2017年 HJQ. All rights reserved.
//
import Foundation
open class JQWeakTimerObject: NSObject {
@objc public weak var targat: AnyObject?
@objc public var selector: Selector?
@objc public var timer: Timer?
@objc public static func scheduledTimerWithTimeInterval(_ interval: TimeInterval,
aTargat: AnyObject,
aSelector: Selector,
userInfo: AnyObject?,
repeats: Bool) -> Timer {
let weakObject = JQWeakTimerObject()
weakObject.targat = aTargat
weakObject.selector = aSelector
weakObject.timer = Timer.scheduledTimer(timeInterval: interval,
target: weakObject,
selector: #selector(fire),
userInfo: userInfo,
repeats: repeats)
return weakObject.timer!
}
@objc public func fire(_ ti: Timer) {
if let _ = targat {
_ = targat?.perform(selector!, with: ti.userInfo)
} else {
timer?.invalidate()
}
}
}
| apache-2.0 | 416bd3f325ed1645e333629d923b5ca4 | 34.3 | 85 | 0.465297 | 5.472868 | false | false | false | false |
insidegui/WWDC | WWDC/TranscriptSearchController.swift | 1 | 5042 | //
// TranscriptSearchController.swift
// WWDC
//
// Created by Guilherme Rambo on 30/05/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ConfCore
import RxSwift
import RxCocoa
import PlayerUI
final class TranscriptSearchController: NSViewController {
enum Style: Int {
case fullWidth
case corner
}
var style: Style = .corner {
didSet {
guard style != oldValue else { return }
updateStyle()
}
}
var showsNewWindowButton: Bool {
get { !detachButton.isHidden }
set { detachButton.isHidden = !newValue }
}
var didSelectOpenInNewWindow: () -> Void = { }
var didSelectExportTranscript: () -> Void = { }
private(set) var searchTerm = BehaviorRelay<String?>(value: nil)
private lazy var detachButton: PUIButton = {
let b = PUIButton(frame: .zero)
b.image = #imageLiteral(resourceName: "window")
b.target = self
b.action = #selector(openInNewWindow)
b.toolTip = "Open Transcript in New Window"
b.setContentHuggingPriority(.defaultHigh, for: .horizontal)
b.widthAnchor.constraint(equalToConstant: 18).isActive = true
b.heightAnchor.constraint(equalToConstant: 14).isActive = true
return b
}()
private lazy var exportButton: NSView = {
let b = PUIButton(frame: .zero)
b.image = #imageLiteral(resourceName: "share")
b.target = self
b.action = #selector(exportTranscript)
b.toolTip = "Export Transcript"
b.setContentHuggingPriority(.defaultHigh, for: .horizontal)
b.translatesAutoresizingMaskIntoConstraints = false
let container = NSView()
container.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(b)
NSLayoutConstraint.activate([
b.widthAnchor.constraint(equalToConstant: 14),
b.heightAnchor.constraint(equalToConstant: 18),
container.widthAnchor.constraint(equalToConstant: 14),
container.heightAnchor.constraint(equalToConstant: 22),
b.centerXAnchor.constraint(equalTo: container.centerXAnchor),
b.centerYAnchor.constraint(equalTo: container.centerYAnchor, constant: -2)
])
return container
}()
private lazy var searchField: NSSearchField = {
let f = NSSearchField()
f.translatesAutoresizingMaskIntoConstraints = false
f.setContentHuggingPriority(.defaultLow, for: .horizontal)
return f
}()
private lazy var stackView: NSStackView = {
let v = NSStackView(views: [self.searchField, self.exportButton, self.detachButton])
v.orientation = .horizontal
v.spacing = 8
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
private lazy var widthConstraint: NSLayoutConstraint = {
view.widthAnchor.constraint(equalToConstant: 226)
}()
static let height: CGFloat = 40
override func loadView() {
view = NSView()
view.wantsLayer = true
view.layer?.cornerCurve = .continuous
view.layer?.backgroundColor = NSColor.roundedCellBackground.cgColor
view.addSubview(stackView)
NSLayoutConstraint.activate([
view.heightAnchor.constraint(equalToConstant: Self.height),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
])
updateStyle()
}
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let throttledSearch = searchField.rx.text.throttle(.milliseconds(500), scheduler: MainScheduler.instance)
throttledSearch.bind(to: searchTerm)
.disposed(by: disposeBag)
// The skip(1) prevents us from clearing the search pasteboard on initial binding.
throttledSearch.skip(1).ignoreNil().subscribe(onNext: { term in
NSPasteboard(name: .find).clearContents()
NSPasteboard(name: .find).setString(term, forType: .string)
}).disposed(by: disposeBag)
}
@objc private func openInNewWindow() {
didSelectOpenInNewWindow()
}
private func updateStyle() {
widthConstraint.isActive = style == .corner
view.layer?.cornerRadius = style == .corner ? 6 : 0
}
override func viewDidAppear() {
super.viewDidAppear()
guard let pasteboardTerm = NSPasteboard(name: .find).string(forType: .string),
pasteboardTerm != searchTerm.value else {
return
}
searchField.stringValue = pasteboardTerm
searchTerm.accept(pasteboardTerm)
}
@objc private func exportTranscript() {
didSelectExportTranscript()
}
}
| bsd-2-clause | 688c32ef91651dc4c91941c12b0de1e1 | 29.551515 | 113 | 0.644515 | 5.133401 | false | false | false | false |
esttorhe/SwiftSSH2 | SwiftSSH2Tests/Supporting Files/SwiftSSH2.playground/Contents.swift | 1 | 473 |
// Native Frameworks
import CFNetwork
import Foundation
//let hostaddr = "google.com"
//let host = CFHostCreateWithName(kCFAllocatorDefault, hostaddr)
//host.autorelease()
//let error = UnsafeMutablePointer<CFStreamError>.alloc(1)
//let tHost: CFHost! = host.takeRetainedValue()
//if CFHostStartInfoResolution(tHost, CFHostInfoType.Addresses, error) {
// let hbr = UnsafeMutablePointer<Boolean>()
// addresses = CFHostGetAddressing(host, hbr)
//}
//
//error.dealloc(1)
| mit | 94210df69302e23583007c658efc798e | 28.5625 | 72 | 0.758985 | 3.583333 | false | false | false | false |
practicalswift/swift | test/decl/protocol/conforms/nscoding.swift | 4 | 7588 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -verify
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -disable-nskeyedarchiver-diagnostics 2>&1 | %FileCheck -check-prefix CHECK-NO-DIAGS %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -dump-ast > %t.ast
// RUN: %FileCheck %s < %t.ast
// REQUIRES: objc_interop
// CHECK-NO-DIAGS-NOT: NSCoding
// CHECK-NO-DIAGS-NOT: unstable
import Foundation
// Top-level classes
// CHECK-NOT: class_decl{{.*}}"CodingA"{{.*}}@_staticInitializeObjCMetadata
class CodingA : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
} // okay
// Nested classes
extension CodingA {
// CHECK-NOT: class_decl{{.*}}"NestedA"{{.*}}@_staticInitializeObjCMetadata
class NestedA : NSObject, NSCoding { // expected-error{{nested class 'CodingA.NestedA' has an unstable name when archiving via 'NSCoding'}}
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedA)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
class NestedB : NSObject {
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedB)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
// CHECK-NOT: class_decl{{.*}}"NestedC"{{.*}}@_staticInitializeObjCMetadata
@objc(CodingA_NestedC)
class NestedC : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
// CHECK-NOT: class_decl{{.*}}"NestedD"{{.*}}@_staticInitializeObjCMetadata
@objc(CodingA_NestedD)
class NestedD : NSObject {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
}
extension CodingA.NestedB: NSCoding { // expected-error{{nested class 'CodingA.NestedB' has an unstable name when archiving via 'NSCoding'}}
}
extension CodingA.NestedD: NSCoding { // okay
}
// Generic classes
// CHECK-NOT: class_decl{{.*}}"CodingB"{{.*}}@_staticInitializeObjCMetadata
class CodingB<T> : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
extension CodingB {
class NestedA : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
}
// Fileprivate classes.
// CHECK-NOT: class_decl{{.*}}"CodingC"{{.*}}@_staticInitializeObjCMetadata
fileprivate class CodingC : NSObject, NSCoding { // expected-error{{fileprivate class 'CodingC' has an unstable name when archiving via 'NSCoding'}}
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingC)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
// Private classes
private class CodingD : NSObject, NSCoding { // expected-error{{private class 'CodingD' has an unstable name when archiving via 'NSCoding'}}
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingD)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
// Local classes.
func someFunction() {
class LocalCoding : NSObject, NSCoding { // expected-error{{local class 'LocalCoding' has an unstable name when archiving via 'NSCoding'}}
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCF8nscoding12someFunctionFT_T_L_11LocalCoding)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
}
// Inherited conformances.
// CHECK-NOT: class_decl{{.*}}"CodingE"{{.*}}@_staticInitializeObjCMetadata
class CodingE<T> : CodingB<T> {
required init(coder: NSCoder) { super.init(coder: coder) }
override func encode(coder: NSCoder) { }
}
// @objc suppressions
@objc(TheCodingF)
fileprivate class CodingF : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
@objc(TheCodingG)
private class CodingG : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
extension CodingB {
// CHECK-NOT: class_decl{{.*}}"GenericViaScope"{{.*}}@_staticInitializeObjCMetadata
@objc(GenericViaScope) // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}}
class GenericViaScope : NSObject { }
}
// Inference of @_staticInitializeObjCMetadata.
// CHECK-NOT: class_decl{{.*}}"SubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata
class SubclassOfCodingA : CodingA { }
// CHECK: class_decl{{.*}}"SubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata
class SubclassOfCodingE : CodingE<Int> { }
// Do not warn when simply inheriting from classes that conform to NSCoding.
// The subclass may never be serialized. But do still infer static
// initialization, just in case.
// CHECK-NOT: class_decl{{.*}}"PrivateSubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata
private class PrivateSubclassOfCodingA : CodingA { }
// CHECK: class_decl{{.*}}"PrivateSubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata
private class PrivateSubclassOfCodingE : CodingE<Int> { }
// But do warn when inherited through a protocol.
protocol AlsoNSCoding : NSCoding {}
private class CodingH : NSObject, AlsoNSCoding { // expected-error{{private class 'CodingH' has an unstable name when archiving via 'NSCoding'}}
// expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingH)}}
// expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}}
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
@NSKeyedArchiverClassName( "abc" ) // expected-error {{@NSKeyedArchiverClassName has been removed; use @objc instead}} {{2-26=objc}} {{28-29=}} {{32-33=}}
class OldArchiverAttribute: NSObject {}
@NSKeyedArchiverEncodeNonGenericSubclassesOnly // expected-error {{@NSKeyedArchiverEncodeNonGenericSubclassesOnly is no longer necessary}} {{1-48=}}
class OldArchiverAttributeGeneric<T>: NSObject {}
// Don't allow one to write @_staticInitializeObjCMetadata!
@_staticInitializeObjCMetadata // expected-error{{unknown attribute '_staticInitializeObjCMetadata'}}
class DontAllowStaticInits { }
| apache-2.0 | 9c606a5a1667369a71b8852c2228a0a4 | 46.72327 | 201 | 0.721139 | 3.714146 | false | false | false | false |
montehurd/apps-ios-wikipedia | WMF Framework/NavigationBar.swift | 1 | 32451 | @objc public enum NavigationBarDisplayType: Int {
case backVisible
case largeTitle
case modal
case hidden
}
@objc(WMFNavigationBar)
public class NavigationBar: SetupView, FakeProgressReceiving, FakeProgressDelegate {
fileprivate let statusBarUnderlay: UIView = UIView()
fileprivate let titleBar: UIToolbar = UIToolbar()
fileprivate let bar: UINavigationBar = UINavigationBar()
fileprivate let underBarView: UIView = UIView() // this is always visible below the navigation bar
fileprivate let extendedView: UIView = UIView()
fileprivate let shadow: UIView = UIView()
fileprivate let progressView: UIProgressView = UIProgressView()
fileprivate let backgroundView: UIView = UIView()
public var underBarViewPercentHiddenForShowingTitle: CGFloat?
public var title: String?
convenience public init() {
self.init(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
}
override init(frame: CGRect) {
super.init(frame: frame)
assert(frame.size != .zero, "Non-zero frame size required to prevent iOS 13 constraint breakage")
titleBar.frame = bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var isAdjustingHidingFromContentInsetChangesEnabled: Bool = true
public var isShadowHidingEnabled: Bool = false // turn on/off shadow alpha adjusment
public var isTitleShrinkingEnabled: Bool = false
public var isInteractiveHidingEnabled: Bool = true // turn on/off any interactive adjustment of bar or view visibility
@objc public var isShadowBelowUnderBarView: Bool = false {
didSet {
updateShadowConstraints()
}
}
public var isShadowShowing: Bool = true {
didSet {
updateShadowHeightConstraintConstant()
}
}
@objc public var isTopSpacingHidingEnabled: Bool = true
@objc public var isBarHidingEnabled: Bool = true
@objc public var isUnderBarViewHidingEnabled: Bool = false
@objc public var isExtendedViewHidingEnabled: Bool = false
@objc public var isExtendedViewFadingEnabled: Bool = true // fade out extended view as it hides
public var shouldTransformUnderBarViewWithBar: Bool = false // hide/show underbar view when bar is hidden/shown // TODO: change this stupid name
public var allowsUnderbarHitsFallThrough: Bool = false //if true, this only considers underBarView's subviews for hitTest, not self. Use if you need underlying view controller's scroll view to capture scrolling.
public var allowsExtendedHitsFallThrough: Bool = false //if true, this only considers extendedView's subviews for hitTest, not self. Use if you need underlying view controller's scroll view to capture scrolling.
private var theme = Theme.standard
public var shadowColorKeyPath: KeyPath<Theme, UIColor> = \Theme.colors.chromeShadow
/// back button presses will be forwarded to this nav controller
@objc public weak var delegate: UIViewController? {
didSet {
updateNavigationItems()
}
}
private var _displayType: NavigationBarDisplayType = .backVisible
@objc public var displayType: NavigationBarDisplayType {
get {
return _displayType
}
set {
guard newValue != _displayType else {
return
}
_displayType = newValue
isTitleShrinkingEnabled = _displayType == .largeTitle
updateTitleBarConstraints()
updateNavigationItems()
updateAccessibilityElements()
}
}
private func updateAccessibilityElements() {
let titleElement = displayType == .largeTitle ? titleBar : bar
accessibilityElements = [titleElement, extendedView, underBarView]
}
@objc public func updateNavigationItems() {
var items: [UINavigationItem] = []
if displayType == .backVisible {
if let vc = delegate, let nc = vc.navigationController {
var indexToAppend: Int = 0
if let index = nc.viewControllers.firstIndex(of: vc), index > 0 {
indexToAppend = index
} else if let parentVC = vc.parent,
let index = nc.viewControllers.firstIndex(of: parentVC),
index > 0 {
indexToAppend = index
}
if indexToAppend > 0 {
items.append(nc.viewControllers[indexToAppend].navigationItem)
}
}
}
if let item = delegate?.navigationItem {
items.append(item)
}
if displayType == .largeTitle, let navigationItem = items.last {
configureTitleBar(with: navigationItem)
} else {
bar.setItems([], animated: false)
bar.setItems(items, animated: false)
}
apply(theme: theme)
}
private var cachedTitleViewItem: UIBarButtonItem?
private var titleView: UIView?
private func configureTitleBar(with navigationItem: UINavigationItem) {
var titleBarItems: [UIBarButtonItem] = []
titleView = nil
if let titleView = navigationItem.titleView {
if let cachedTitleViewItem = cachedTitleViewItem {
titleBarItems.append(cachedTitleViewItem)
} else {
let titleItem = UIBarButtonItem(customView: titleView)
titleBarItems.append(titleItem)
cachedTitleViewItem = titleItem
}
} else if let title = navigationItem.title {
let navigationTitleLabel = UILabel()
navigationTitleLabel.text = title
navigationTitleLabel.sizeToFit()
navigationTitleLabel.font = UIFont.wmf_font(.boldTitle1)
titleView = navigationTitleLabel
let titleItem = UIBarButtonItem(customView: navigationTitleLabel)
titleBarItems.append(titleItem)
}
titleBarItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
if let item = navigationItem.leftBarButtonItem {
let leftBarButtonItem = barButtonItem(from: item)
titleBarItems.append(leftBarButtonItem)
}
if let item = navigationItem.rightBarButtonItem {
let rightBarButtonItem = barButtonItem(from: item)
titleBarItems.append(rightBarButtonItem)
}
titleBar.setItems(titleBarItems, animated: false)
}
// HAX: barButtonItem that we're getting from the navigationItem will not be shown on iOS 11 so we need to recreate it
private func barButtonItem(from item: UIBarButtonItem) -> UIBarButtonItem {
let barButtonItem: UIBarButtonItem
if let title = item.title {
barButtonItem = UIBarButtonItem(title: title, style: item.style, target: item.target, action: item.action)
} else if let systemBarButton = item as? SystemBarButton, let systemItem = systemBarButton.systemItem {
barButtonItem = SystemBarButton(with: systemItem, target: systemBarButton.target, action: systemBarButton.action)
} else if let customView = item.customView {
let customViewData = NSKeyedArchiver.archivedData(withRootObject: customView)
if let copiedView = NSKeyedUnarchiver.unarchiveObject(with: customViewData) as? UIView {
if let button = customView as? UIButton, let copiedButton = copiedView as? UIButton {
for target in button.allTargets {
guard let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside) else {
continue
}
for action in actions {
copiedButton.addTarget(target, action: Selector(action), for: .touchUpInside)
}
}
}
barButtonItem = UIBarButtonItem(customView: copiedView)
} else {
assert(false, "unable to copy custom view")
barButtonItem = item
}
} else if let image = item.image {
barButtonItem = UIBarButtonItem(image: image, landscapeImagePhone: item.landscapeImagePhone, style: item.style, target: item.target, action: item.action)
} else {
assert(false, "barButtonItem must have title OR be of type SystemBarButton OR have image OR have custom view")
barButtonItem = item
}
barButtonItem.isEnabled = item.isEnabled
barButtonItem.isAccessibilityElement = item.isAccessibilityElement
barButtonItem.accessibilityLabel = item.accessibilityLabel
return barButtonItem
}
private var titleBarHeightConstraint: NSLayoutConstraint!
private var underBarViewHeightConstraint: NSLayoutConstraint!
private var shadowTopUnderBarViewBottomConstraint: NSLayoutConstraint!
private var shadowTopExtendedViewBottomConstraint: NSLayoutConstraint!
private var shadowHeightConstraint: NSLayoutConstraint!
private var extendedViewHeightConstraint: NSLayoutConstraint!
private var titleBarTopConstraint: NSLayoutConstraint!
private var barTopConstraint: NSLayoutConstraint!
public var barTopSpacing: CGFloat = 0 {
didSet {
titleBarTopConstraint.constant = barTopSpacing
barTopConstraint.constant = barTopSpacing
setNeedsLayout()
}
}
var underBarViewTopBarBottomConstraint: NSLayoutConstraint!
var underBarViewTopTitleBarBottomConstraint: NSLayoutConstraint!
var underBarViewTopBottomConstraint: NSLayoutConstraint!
override open func setup() {
super.setup()
translatesAutoresizingMaskIntoConstraints = false
backgroundView.translatesAutoresizingMaskIntoConstraints = false
statusBarUnderlay.translatesAutoresizingMaskIntoConstraints = false
bar.translatesAutoresizingMaskIntoConstraints = false
underBarView.translatesAutoresizingMaskIntoConstraints = false
extendedView.translatesAutoresizingMaskIntoConstraints = false
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.alpha = 0
shadow.translatesAutoresizingMaskIntoConstraints = false
titleBar.translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
addSubview(extendedView)
addSubview(underBarView)
addSubview(bar)
addSubview(titleBar)
addSubview(progressView)
addSubview(statusBarUnderlay)
addSubview(shadow)
updateAccessibilityElements()
bar.delegate = self
shadowHeightConstraint = shadow.heightAnchor.constraint(equalToConstant: 0.5)
shadowHeightConstraint.priority = .defaultHigh
shadow.addConstraint(shadowHeightConstraint)
var updatedConstraints: [NSLayoutConstraint] = []
let statusBarUnderlayTopConstraint = topAnchor.constraint(equalTo: statusBarUnderlay.topAnchor)
updatedConstraints.append(statusBarUnderlayTopConstraint)
let statusBarUnderlayBottomConstraint = safeAreaLayoutGuide.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor)
updatedConstraints.append(statusBarUnderlayBottomConstraint)
let statusBarUnderlayLeadingConstraint = leadingAnchor.constraint(equalTo: statusBarUnderlay.leadingAnchor)
updatedConstraints.append(statusBarUnderlayLeadingConstraint)
let statusBarUnderlayTrailingConstraint = trailingAnchor.constraint(equalTo: statusBarUnderlay.trailingAnchor)
updatedConstraints.append(statusBarUnderlayTrailingConstraint)
titleBarHeightConstraint = titleBar.heightAnchor.constraint(equalToConstant: 44)
titleBarHeightConstraint.priority = UILayoutPriority(rawValue: 999)
titleBar.addConstraint(titleBarHeightConstraint)
titleBarTopConstraint = titleBar.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor, constant: barTopSpacing)
let titleBarLeadingConstraint = leadingAnchor.constraint(equalTo: titleBar.leadingAnchor)
let titleBarTrailingConstraint = trailingAnchor.constraint(equalTo: titleBar.trailingAnchor)
barTopConstraint = bar.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor, constant: barTopSpacing)
let barLeadingConstraint = leadingAnchor.constraint(equalTo: bar.leadingAnchor)
let barTrailingConstraint = trailingAnchor.constraint(equalTo: bar.trailingAnchor)
underBarViewHeightConstraint = underBarView.heightAnchor.constraint(equalToConstant: 0)
underBarView.addConstraint(underBarViewHeightConstraint)
underBarViewTopBarBottomConstraint = bar.bottomAnchor.constraint(equalTo: underBarView.topAnchor)
underBarViewTopTitleBarBottomConstraint = titleBar.bottomAnchor.constraint(equalTo: underBarView.topAnchor)
underBarViewTopBottomConstraint = topAnchor.constraint(equalTo: underBarView.topAnchor)
let underBarViewLeadingConstraint = leadingAnchor.constraint(equalTo: underBarView.leadingAnchor)
let underBarViewTrailingConstraint = trailingAnchor.constraint(equalTo: underBarView.trailingAnchor)
extendedViewHeightConstraint = extendedView.heightAnchor.constraint(equalToConstant: 0)
extendedView.addConstraint(extendedViewHeightConstraint)
let extendedViewTopConstraint = underBarView.bottomAnchor.constraint(equalTo: extendedView.topAnchor)
let extendedViewLeadingConstraint = leadingAnchor.constraint(equalTo: extendedView.leadingAnchor)
let extendedViewTrailingConstraint = trailingAnchor.constraint(equalTo: extendedView.trailingAnchor)
let extendedViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: bottomAnchor)
let backgroundViewTopConstraint = topAnchor.constraint(equalTo: backgroundView.topAnchor)
let backgroundViewLeadingConstraint = leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor)
let backgroundViewTrailingConstraint = trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor)
let backgroundViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor)
let progressViewBottomConstraint = shadow.topAnchor.constraint(equalTo: progressView.bottomAnchor, constant: 1)
let progressViewLeadingConstraint = leadingAnchor.constraint(equalTo: progressView.leadingAnchor)
let progressViewTrailingConstraint = trailingAnchor.constraint(equalTo: progressView.trailingAnchor)
let shadowLeadingConstraint = leadingAnchor.constraint(equalTo: shadow.leadingAnchor)
let shadowTrailingConstraint = trailingAnchor.constraint(equalTo: shadow.trailingAnchor)
shadowTopExtendedViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: shadow.topAnchor)
shadowTopUnderBarViewBottomConstraint = underBarView.bottomAnchor.constraint(equalTo: shadow.topAnchor)
updatedConstraints.append(contentsOf: [titleBarTopConstraint, titleBarLeadingConstraint, titleBarTrailingConstraint, underBarViewTopTitleBarBottomConstraint, barTopConstraint, barLeadingConstraint, barTrailingConstraint, underBarViewTopBarBottomConstraint, underBarViewTopBottomConstraint, underBarViewLeadingConstraint, underBarViewTrailingConstraint, extendedViewTopConstraint, extendedViewLeadingConstraint, extendedViewTrailingConstraint, extendedViewBottomConstraint, backgroundViewTopConstraint, backgroundViewLeadingConstraint, backgroundViewTrailingConstraint, backgroundViewBottomConstraint, progressViewBottomConstraint, progressViewLeadingConstraint, progressViewTrailingConstraint, shadowTopUnderBarViewBottomConstraint, shadowTopExtendedViewBottomConstraint, shadowLeadingConstraint, shadowTrailingConstraint])
addConstraints(updatedConstraints)
updateTitleBarConstraints()
updateShadowConstraints()
updateShadowHeightConstraintConstant()
setNavigationBarPercentHidden(0, underBarViewPercentHidden: 0, extendedViewPercentHidden: 0, topSpacingPercentHidden: 0, animated: false)
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateShadowHeightConstraintConstant()
}
private func updateShadowHeightConstraintConstant() {
guard traitCollection.displayScale > 0 else {
return
}
if !isShadowShowing {
shadowHeightConstraint.constant = 0
} else {
shadowHeightConstraint.constant = 1.0 / traitCollection.displayScale
}
}
fileprivate var _topSpacingPercentHidden: CGFloat = 0
@objc public var topSpacingPercentHidden: CGFloat {
get {
return _topSpacingPercentHidden
}
set {
setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: newValue, animated: false)
}
}
fileprivate var _navigationBarPercentHidden: CGFloat = 0
@objc public var navigationBarPercentHidden: CGFloat {
get {
return _navigationBarPercentHidden
}
set {
setNavigationBarPercentHidden(newValue, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false)
}
}
private var _underBarViewPercentHidden: CGFloat = 0
@objc public var underBarViewPercentHidden: CGFloat {
get {
return _underBarViewPercentHidden
}
set {
setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: newValue, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false)
}
}
fileprivate var _extendedViewPercentHidden: CGFloat = 0
@objc public var extendedViewPercentHidden: CGFloat {
get {
return _extendedViewPercentHidden
}
set {
setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: newValue, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false)
}
}
@objc dynamic public var visibleHeight: CGFloat = 0
@objc dynamic public var insetTop: CGFloat = 0
@objc public var hiddenHeight: CGFloat = 0
public var shadowAlpha: CGFloat {
get {
return shadow.alpha
}
set {
shadow.alpha = newValue
}
}
@objc public func setNavigationBarPercentHidden(_ navigationBarPercentHidden: CGFloat, underBarViewPercentHidden: CGFloat, extendedViewPercentHidden: CGFloat, topSpacingPercentHidden: CGFloat, shadowAlpha: CGFloat = -1, animated: Bool, additionalAnimations: (() -> Void)? = nil) {
if (animated) {
layoutIfNeeded()
}
if isTopSpacingHidingEnabled {
_topSpacingPercentHidden = topSpacingPercentHidden
}
if isBarHidingEnabled {
_navigationBarPercentHidden = navigationBarPercentHidden
}
if isUnderBarViewHidingEnabled {
_underBarViewPercentHidden = underBarViewPercentHidden
}
if isExtendedViewHidingEnabled {
_extendedViewPercentHidden = extendedViewPercentHidden
}
setNeedsLayout()
//print("nb: \(navigationBarPercentHidden) ev: \(extendedViewPercentHidden)")
let applyChanges = {
let changes = {
if shadowAlpha >= 0 {
self.shadowAlpha = shadowAlpha
}
if (animated) {
self.layoutIfNeeded()
}
additionalAnimations?()
}
if animated {
UIView.animate(withDuration: 0.2, animations: changes)
} else {
changes()
}
}
if let underBarViewPercentHiddenForShowingTitle = self.underBarViewPercentHiddenForShowingTitle {
UIView.animate(withDuration: 0.2, animations: {
self.delegate?.title = underBarViewPercentHidden >= underBarViewPercentHiddenForShowingTitle ? self.title : nil
}, completion: { (_) in
applyChanges()
})
} else {
applyChanges()
}
}
private func updateTitleBarConstraints() {
let isUsingTitleBarInsteadOfNavigationBar = displayType == .largeTitle
underBarViewTopTitleBarBottomConstraint.isActive = isUsingTitleBarInsteadOfNavigationBar
underBarViewTopBarBottomConstraint.isActive = !isUsingTitleBarInsteadOfNavigationBar && displayType != .hidden
underBarViewTopBottomConstraint.isActive = displayType == .hidden
bar.isHidden = isUsingTitleBarInsteadOfNavigationBar || displayType == .hidden
titleBar.isHidden = !isUsingTitleBarInsteadOfNavigationBar || displayType == .hidden
updateBarTopSpacing()
setNeedsUpdateConstraints()
}
public override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
updateBarTopSpacing()
}
// collapse bar top spacing if there's no status bar
private func updateBarTopSpacing() {
guard displayType == .largeTitle else {
barTopSpacing = 0
return
}
let isSafeAreaInsetsTopGreaterThanZero = safeAreaInsets.top > 0
barTopSpacing = isSafeAreaInsetsTopGreaterThanZero ? 30 : 0
titleBarHeightConstraint.constant = isSafeAreaInsetsTopGreaterThanZero ? 44 : 32 // it doesn't seem like there's a way to force update of bar metrics - as it stands the bar height gets stuck in whatever mode the app was launched in
}
private func updateShadowConstraints() {
shadowTopUnderBarViewBottomConstraint.isActive = isShadowBelowUnderBarView
shadowTopExtendedViewBottomConstraint.isActive = !isShadowBelowUnderBarView
setNeedsUpdateConstraints()
}
var barHeight: CGFloat {
return (displayType == .largeTitle ? titleBar.frame.height : bar.frame.height)
}
var underBarViewHeight: CGFloat {
return underBarView.frame.size.height
}
var extendedViewHeight: CGFloat {
return extendedView.frame.size.height
}
var topSpacingHideableHeight: CGFloat {
return isTopSpacingHidingEnabled ? barTopSpacing : 0
}
var barHideableHeight: CGFloat {
return isBarHidingEnabled ? barHeight : 0
}
var underBarViewHideableHeight: CGFloat {
return isUnderBarViewHidingEnabled ? underBarViewHeight : 0
}
var extendedViewHideableHeight: CGFloat {
return isExtendedViewHidingEnabled ? extendedViewHeight : 0
}
var hideableHeight: CGFloat {
return topSpacingHideableHeight + barHideableHeight + underBarViewHideableHeight + extendedViewHideableHeight
}
public override func layoutSubviews() {
super.layoutSubviews()
let navigationBarPercentHidden = _navigationBarPercentHidden
let extendedViewPercentHidden = _extendedViewPercentHidden
let underBarViewPercentHidden = _underBarViewPercentHidden
let topSpacingPercentHidden = safeAreaInsets.top > 0 ? _topSpacingPercentHidden : 1 // treat top spacing as hidden if there's no status bar so that the title is smaller
let underBarViewHeight = underBarView.frame.height
let barHeight = self.barHeight
let extendedViewHeight = extendedView.frame.height
visibleHeight = statusBarUnderlay.frame.size.height + barHeight * (1.0 - navigationBarPercentHidden) + extendedViewHeight * (1.0 - extendedViewPercentHidden) + underBarViewHeight * (1.0 - underBarViewPercentHidden) + (barTopSpacing * (1.0 - topSpacingPercentHidden))
let spacingTransformHeight = barTopSpacing * topSpacingPercentHidden
let barTransformHeight = barHeight * navigationBarPercentHidden + spacingTransformHeight
let extendedViewTransformHeight = extendedViewHeight * extendedViewPercentHidden
let underBarTransformHeight = underBarViewHeight * underBarViewPercentHidden
hiddenHeight = barTransformHeight + extendedViewTransformHeight + underBarTransformHeight
let barTransform = CGAffineTransform(translationX: 0, y: 0 - barTransformHeight)
let barScaleTransform = CGAffineTransform(scaleX: 1.0 - navigationBarPercentHidden * navigationBarPercentHidden, y: 1.0 - navigationBarPercentHidden * navigationBarPercentHidden)
self.bar.transform = barTransform
self.titleBar.transform = barTransform
if isTitleShrinkingEnabled {
let titleScale: CGFloat = 1.0 - 0.2 * topSpacingPercentHidden
self.titleView?.transform = CGAffineTransform(scaleX: titleScale, y: titleScale)
}
for subview in self.bar.subviews {
for subview in subview.subviews {
subview.transform = barScaleTransform
}
}
self.bar.alpha = min(backgroundAlpha, (1.0 - 2.0 * navigationBarPercentHidden).wmf_normalizedPercentage)
self.titleBar.alpha = self.bar.alpha
let totalTransform = CGAffineTransform(translationX: 0, y: 0 - hiddenHeight)
self.backgroundView.transform = totalTransform
let underBarTransform = CGAffineTransform(translationX: 0, y: 0 - barTransformHeight - underBarTransformHeight)
self.underBarView.transform = underBarTransform
self.underBarView.alpha = 1.0 - underBarViewPercentHidden
self.extendedView.transform = totalTransform
if isExtendedViewFadingEnabled {
self.extendedView.alpha = min(backgroundAlpha, 1.0 - extendedViewPercentHidden)
} else {
self.extendedView.alpha = CGFloat(1).isLessThanOrEqualTo(extendedViewPercentHidden) ? 0 : backgroundAlpha
}
self.progressView.transform = isShadowBelowUnderBarView ? underBarTransform : totalTransform
self.shadow.transform = isShadowBelowUnderBarView ? underBarTransform : totalTransform
// HAX: something odd going on with iOS 11...
insetTop = backgroundView.frame.origin.y
if #available(iOS 12, *) {
insetTop = visibleHeight
}
}
@objc public func setProgressHidden(_ hidden: Bool, animated: Bool) {
let changes = {
self.progressView.alpha = min(hidden ? 0 : 1, self.backgroundAlpha)
}
if animated {
UIView.animate(withDuration: 0.2, animations: changes)
} else {
changes()
}
}
@objc public func setProgress(_ progress: Float, animated: Bool) {
progressView.setProgress(progress, animated: animated)
}
@objc public var progress: Float {
get {
return progressView.progress
}
set {
progressView.progress = newValue
}
}
@objc public func addExtendedNavigationBarView(_ view: UIView) {
guard extendedView.subviews.first == nil else {
return
}
extendedViewHeightConstraint.isActive = false
extendedView.wmf_addSubviewWithConstraintsToEdges(view)
}
@objc public func removeExtendedNavigationBarView() {
guard let subview = extendedView.subviews.first else {
return
}
subview.removeFromSuperview()
extendedViewHeightConstraint.isActive = true
}
@objc public func addUnderNavigationBarView(_ view: UIView) {
guard underBarView.subviews.first == nil else {
return
}
underBarViewHeightConstraint.isActive = false
underBarView.wmf_addSubviewWithConstraintsToEdges(view)
}
@objc public func removeUnderNavigationBarView() {
guard let subview = underBarView.subviews.first else {
return
}
subview.removeFromSuperview()
underBarViewHeightConstraint.isActive = true
}
@objc public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if allowsUnderbarHitsFallThrough
&& underBarView.frame.contains(point)
&& !bar.frame.contains(point) {
for subview in underBarView.subviews {
let convertedPoint = self.convert(point, to: subview)
if subview.point(inside: convertedPoint, with: event) {
return true
}
}
return false
}
if allowsExtendedHitsFallThrough
&& extendedView.frame.contains(point)
&& !bar.frame.contains(point) {
for subview in extendedView.subviews {
let convertedPoint = self.convert(point, to: subview)
if subview.point(inside: convertedPoint, with: event) {
return true
}
}
return false
}
return point.y <= visibleHeight
}
public var backgroundAlpha: CGFloat = 1 {
didSet {
statusBarUnderlay.alpha = backgroundAlpha
backgroundView.alpha = backgroundAlpha
bar.alpha = backgroundAlpha
titleBar.alpha = backgroundAlpha
extendedView.alpha = backgroundAlpha
if backgroundAlpha < progressView.alpha {
progressView.alpha = backgroundAlpha
}
}
}
}
extension NavigationBar: Themeable {
public func apply(theme: Theme) {
self.theme = theme
backgroundColor = .clear
statusBarUnderlay.backgroundColor = theme.colors.paperBackground
backgroundView.backgroundColor = theme.colors.paperBackground
titleBar.setBackgroundImage(theme.navigationBarBackgroundImage, forToolbarPosition: .any, barMetrics: .default)
titleBar.isTranslucent = false
titleBar.tintColor = theme.colors.chromeText
titleBar.setShadowImage(theme.navigationBarShadowImage, forToolbarPosition: .any)
titleBar.barTintColor = theme.colors.chromeBackground
if let items = titleBar.items {
for item in items {
if let label = item.customView as? UILabel {
label.textColor = theme.colors.chromeText
} else if item.image == nil {
item.tintColor = theme.colors.link
}
}
}
bar.setBackgroundImage(theme.navigationBarBackgroundImage, for: .default)
bar.titleTextAttributes = theme.navigationBarTitleTextAttributes
bar.isTranslucent = false
bar.barTintColor = theme.colors.chromeBackground
bar.shadowImage = theme.navigationBarShadowImage
bar.tintColor = theme.colors.chromeText
extendedView.backgroundColor = .clear
underBarView.backgroundColor = .clear
shadow.backgroundColor = theme[keyPath: shadowColorKeyPath]
progressView.progressViewStyle = .bar
progressView.trackTintColor = .clear
progressView.progressTintColor = theme.colors.link
}
}
extension NavigationBar: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
delegate?.navigationController?.popViewController(animated: true)
return false
}
}
| mit | dcdb0ee2cf64960a1e674e2c2acea959 | 43.698347 | 831 | 0.680287 | 5.756786 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 10/AbstractFactory/AbstractFactory/Floorplans.swift | 1 | 472 | protocol Floorplan {
var seats:Int { get }
var enginePosition:EngineOption { get };
}
enum EngineOption : String {
case FRONT = "Front"; case MID = "Mid";
}
class ShortFloorplan: Floorplan {
var seats = 2;
var enginePosition = EngineOption.MID
}
class StandardFloorplan: Floorplan {
var seats = 4;
var enginePosition = EngineOption.FRONT;
}
class LongFloorplan: Floorplan {
var seats = 8;
var enginePosition = EngineOption.FRONT;
}
| mit | bae4e518f8d98ec19ad3f28eaae44019 | 19.521739 | 44 | 0.682203 | 3.603053 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/MaskShapeLayerVC.swift | 1 | 6364 | //
// MaskShapeLayerVC.swift
// UIScrollViewDemo
//
// Created by xiAo_Ju on 2018/10/27.
// Copyright © 2018 伯驹 黄. All rights reserved.
//
import UIKit
class MaskShapeLayerVC: UIViewController {
var draftShapeLayer : CAShapeLayer?
var squareShapeLayer : CAShapeLayer?
var lineShapeLayer : CAShapeLayer?
var shapeLayer : CAShapeLayer?
let width : CGFloat = 240
let height : CGFloat = 240
lazy var containerLayer : CALayer = { () -> CALayer in
let containerLayer = CALayer()
containerLayer.frame = CGRect(x: self.view.center.x - self.width / 2, y: self.view.center.y - self.height / 2, width: self.width, height: self.height)
self.view.layer.addSublayer(containerLayer)
return containerLayer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// drawHeader()
drawMask()
}
// MARK: - 绘制蒙版
private func drawMask() {
let bgView = UIImageView(image: UIImage(named: "007.jpg"))
bgView.frame = view.bounds
view.addSubview(bgView)
let maskView = UIView(frame: view.bounds)
maskView.backgroundColor = UIColor.red.withAlphaComponent(0.3)
maskView.alpha = 0.8
// view.addSubview(maskView)
let bpath = UIBezierPath(roundedRect: CGRect(x: 10, y: 10, width: view.bounds.width - 20, height: view.bounds.height - 20), cornerRadius: 15)
let circlePath = UIBezierPath(arcCenter: view.center, radius: 100, startAngle: 0, endAngle: .pi * 2, clockwise: false)
bpath.append(circlePath)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.path = bpath.cgPath
// view.layer.addSublayer(shapeLayer)
bgView.layer.mask = shapeLayer
}
// MARK: - 图形动画
private func drawHeader() {
// let draftPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: height), cornerRadius: 5)
let cornerRadius : CGFloat = 20
let draftPath = UIBezierPath()
draftPath.move(to: CGPoint(x: width - cornerRadius, y: 0))
draftPath.addLine(to: CGPoint(x: cornerRadius, y: 0))
draftPath.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: -.pi/2, endAngle: .pi, clockwise: false)
draftPath.addLine(to: CGPoint(x: 0, y: height - cornerRadius))
draftPath.addArc(withCenter: CGPoint(x: cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .pi, endAngle: .pi/2, clockwise: false)
draftPath.addLine(to: CGPoint(x: width - cornerRadius, y: height))
draftPath.addArc(withCenter: CGPoint(x: width - cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .pi/2, endAngle: 0, clockwise: false)
draftPath.addLine(to: CGPoint(x: width, y: cornerRadius))
draftPath.addArc(withCenter: CGPoint(x: width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: 0, endAngle: -.pi/2, clockwise: false)
let margin : CGFloat = 24
let smallSquareWH : CGFloat = 84
let squarePath = UIBezierPath(roundedRect: CGRect(x: margin, y: margin, width: smallSquareWH, height: smallSquareWH), cornerRadius: 2)
let shortLineLeft : CGFloat = margin * 2 + smallSquareWH
let shortLineRight : CGFloat = width - margin
let space : CGFloat = smallSquareWH / 2 - 3
let linePath = UIBezierPath()
for i in 0 ..< 3 {
linePath.move(to: CGPoint(x: shortLineLeft, y: margin + 2 + space * CGFloat(i)))
linePath.addLine(to: CGPoint(x: shortLineRight, y: margin + 2 + space * CGFloat(i)))
}
let longLineRight = width - margin
for i in 0 ..< 3 {
linePath.move(to: CGPoint(x: margin, y: margin * 2 + 2 + smallSquareWH + space * CGFloat(i)))
linePath.addLine(to: CGPoint(x: longLineRight, y: margin * 2 + 2 + smallSquareWH + space * CGFloat(i)))
}
self.draftShapeLayer = CAShapeLayer()
self.draftShapeLayer!.frame = CGRect(x: 0, y: 0, width: width, height: height)
setupShapeLayer(shapeLayer: self.draftShapeLayer!, path: draftPath.cgPath)
self.squareShapeLayer = CAShapeLayer()
self.squareShapeLayer!.frame = CGRect(x: 0, y: 0, width: smallSquareWH, height: smallSquareWH)
setupShapeLayer(shapeLayer: self.squareShapeLayer!, path: squarePath.cgPath)
self.lineShapeLayer = CAShapeLayer()
self.lineShapeLayer!.frame = CGRect(x: 0, y: 0, width: width, height: height)
setupShapeLayer(shapeLayer: self.lineShapeLayer!, path: linePath.cgPath)
addSlider()
}
private func addSlider() {
let slider = UISlider(frame: CGRect(x: 20, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width - 40, height: 10))
slider.minimumValue = 0
slider.maximumValue = 1
slider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: UIControl.Event.valueChanged)
view.addSubview(slider)
}
@objc private func sliderValueChanged(sender: UISlider) {
guard let draftShapeLayer = self.draftShapeLayer else {
return
}
guard let squareShapeLayer = self.squareShapeLayer else {
return
}
guard let lineShapeLayer = self.lineShapeLayer else {
return
}
draftShapeLayer.strokeEnd = CGFloat(sender.value)
squareShapeLayer.strokeEnd = CGFloat(sender.value)
lineShapeLayer.strokeEnd = CGFloat(sender.value)
}
// MARK: - 辅助方法
private func setupShapeLayer(shapeLayer : CAShapeLayer, path : CGPath) {
shapeLayer.path = path
shapeLayer.strokeColor = UIColor.gray.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.lineWidth = 2
shapeLayer.strokeStart = 0
shapeLayer.strokeEnd = 0
containerLayer.addSublayer(shapeLayer)
}
}
| mit | ef8ad83a8280631c57190a780783c608 | 39.858065 | 168 | 0.627823 | 4.404033 | false | false | false | false |
zhangdadi/SwiftHttp | HDNetwork/HDNetwork/Network/HDNetDataThread.swift | 1 | 6685 | //
// HDNetDataThread.swift
// HDNetFramework
//
// Created by 张达棣 on 14-8-3.
// Copyright (c) 2014年 HD. All rights reserved.
//
// 若发现bug请致电:[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
/**
* 全局的数据线程单例
*/
struct DataThreadInitSingleton{
static func shareInstance() -> HDNetDataThread
{
struct Singleton{
static var predicate: dispatch_once_t = 0
static var instance: HDNetDataThread?
}
dispatch_once(&Singleton.predicate, {
func gDataThreadInit() -> HDNetDataThread {
var len: UInt = 0
var ncpu: UInt = 0
len = UInt(sizeofValue(ncpu))
// sysctlbyname("hw.ncpu", &ncpu, &len, nil, 0)
if ncpu <= 1 {
debugPrintln("network in main thread")
return HDNetDataThread()
} else {
debugPrintln("network multithreaded")
return HDNetDataThread()
}
}
Singleton.instance = gDataThreadInit()
})
return Singleton.instance!
}
//判断当前线程是否为数据线程
static func isDataThread() -> Bool {
return NSThread.currentThread().isEqual(DataThreadInitSingleton.shareInstance())
}
}
//________________________________________________________________________________________
/**
* 全局队列
*/
struct QueueSingleton {
static func shareInstance() -> HDNetRequestQueue {
struct Singleton{
static var predicate: dispatch_once_t = 0
static var instance: HDNetRequestQueue? = nil
}
dispatch_once(&Singleton.predicate, {
Singleton.instance = HDNetRequestQueue()
})
return Singleton.instance!
}
}
//_________________________________________________________________
/**
* 数据线程
*/
class HDNetDataThread: NSThread {
typealias Call = () -> ()
typealias CallParm = (i: Int) -> ()
var onCall: Call? {
set {
_callList.append(newValue!)
}
get {
return nil
}
}
func setOnCallParm(callParm: CallParm, parm: Int) {
_callParmList.append(callParm)
_parmList.append(parm);
}
var _callList = [Call]()
var _callParmList = [CallParm]()
var _parmList = [Int]()
init(sender: HDNetDataThread) {
}
convenience override init() {
self.init(sender: self)
self.start()
}
override func main() {
// 数据线程优先级调低(界面线程应该是0.5)
NSThread.setThreadPriority(0.3)
var i = 0
while true {
if _callList.count > 0 {
_callList[0]()
let v = _callList.removeAtIndex(0)
}
if _callParmList.count > 0 {
_callParmList[0](i: _parmList[0])
let v = _callList.removeAtIndex(0)
let p = _parmList.removeAtIndex(0);
}
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
}
//_________________________________________________________________
/**
* 多点回调
*/
//class HDNetCallNode: NSObject {
// weak var _data: HDNetCtrlDelegate?
// var _next: HDNetCallNode?
//
// func push(data: HDNetCtrlDelegate) {
// pop(data)
// var temp = self
// while temp._next != nil {
// temp = temp._next!
// }
// var newNode = HDNetCallNode()
// newNode._data = data
// temp._next = newNode
// }
//
// func pop(index:Int) {
// var lastTemp: HDNetCallNode? = self
// var temp: HDNetCallNode? = self._next
// var i = 0
// while lastTemp?._next != nil && i <= index {
// if i == index {
// lastTemp?._next = temp?._next
// temp?._data = nil
// temp = nil
// }
// lastTemp = lastTemp?._next
// temp = temp?._next
// ++i
// }
// }
//
// func pop(data: HDNetCtrlDelegate) {
// var lastTemp: HDNetCallNode? = self
// var temp: HDNetCallNode? = self._next
//
// while lastTemp?._next != nil {
// if data === temp?._data {
// lastTemp?._next = temp?._next
// temp?._data = nil
// temp = nil
// }
// lastTemp = lastTemp?._next
// temp = temp?._next
// }
// }
//
// func callUpdate(sender: HDNetDataModel) {
// var temp = self
// var i = 0
// while temp._next != nil {
// temp = temp._next!
// if temp._data != nil {
// temp._data?.netCtrlUpdate?(sender)
// } else {
// pop(i)
// }
// ++i
// }
// }
//
// func callProgress(sender: HDNetDataModel) {
// var temp = self
// while temp._next != nil {
// temp = temp._next!
// temp._data?.netCtrlProgress?(sender)
// }
// }
//
// func _find(data:HDNetCtrlDelegate) -> Bool {
// var temp = self
// while temp._next != nil {
// temp = temp._next!
// if temp._data === data {
// return true
// }
// }
// return false
// }
//}
| mit | 11dc3bafca824213fa4a89a0b51e7cf4 | 27.572052 | 115 | 0.505426 | 4.016575 | false | false | false | false |
PezHead/tiny-tennis-scoreboard | TableTennisAPI/TableTennisAPI/ImageStore.swift | 1 | 2963 | //
// ImageStore.swift
// Tiny Tennis
//
// Created by David Bireta on 10/20/16.
// Copyright © 2016 David Bireta. All rights reserved.
//
/// Provides access to all images.
/// Currently this is just champion avatars.
class ImageStore {
static let shared = ImageStore()
/// Upon initialization, an "Images" directory will be created.
fileprivate init() {
if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let imagesDirPath = documentsPath.appendingPathComponent("Images", isDirectory: true)
do {
// Per Apple recommendations, always try to create the folder instead of checking if it already exists first.
try FileManager.default.createDirectory(at: imagesDirPath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
// Ignore "directory already exists" error
if error.code != 516 {
print("Error creating /Images directory: \(error)")
}
}
}
}
/// Returns an avatar for a given champion. This will look for images in the following order:
/// * Check to see if a downloaded image has been cached in the 'Documents/Images' directory
/// * Check to see if there is an image in the bundle matching the champion's nickname
/// * Attempt to download (and subsequently cache) and image using the `avatar` property
///
/// - parameter champion: The `Champion` for which the image is being requested.
///
/// - returns: Matching avatar image if found, else returns the "default.png" image.
func avatar(for champion: Champion) -> UIImage {
var avatarImage = UIImage(named: "default")!
if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let imagesDirPath = documentsPath.appendingPathComponent("Images", isDirectory: true)
let imagePath = imagesDirPath.appendingPathComponent("\(champion.id).jpg")
if let image = UIImage(contentsOfFile: imagePath.path) {
avatarImage = image
} else if champion.avatar == "" {
if let lastName = champion.lastName, let image = UIImage(named: lastName) {
avatarImage = image
}
} else if let avatarURL = URL(string: champion.avatar), let imageData = try? Data(contentsOf: avatarURL), let image = UIImage(data: imageData) {
// "Cache" it to disk
do {
try imageData.write(to: imagePath, options: .atomic)
} catch let error {
print("Error caching image to disk: \(error)")
}
avatarImage = image
}
}
return avatarImage
}
}
| mit | cf0b87a8a4ce504996ba30d779df88eb | 43.208955 | 156 | 0.599257 | 5.133449 | false | false | false | false |
embryoconcepts/TIY-Assignments | 03a -- MissionBriefing/MissionBriefing/MissionBriefingViewController.swift | 1 | 3153 | //
// ViewController.swift
// MissionBriefing
//
// Created by Jennifer Hamilton on 10/7/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class MissionBriefingViewController: UIViewController, UITextFieldDelegate
{
// Place IBOutlet properties below
@IBOutlet var nameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var authenticateButton: UIButton!
@IBOutlet var greetingLabel: UILabel!
@IBOutlet var missionTextView: UITextView!
override func viewDidLoad()
{
super.viewDidLoad()
// # 3
nameTextField.text = ""
passwordTextField.text = ""
greetingLabel.text = ""
missionTextView.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Action Handlers
@IBAction func buttonTapped(sender: UIButton)
{
authenticateAgent()
}
// MARK: - UITextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
return authenticateAgent()
}
// MARK: - Private
func authenticateAgent() -> Bool
{
var rc = false
if nameTextField.text != ""
{
let name = nameTextField.text
// #4
if passwordTextField.text != ""
{
rc = true
nameTextField.resignFirstResponder()
let nameComponents = name!.characters.split(" ").map { String($0) }
let lastName = nameComponents[1].capitalizedString
// #5
greetingLabel.text = "Good evening, Agent \(lastName)"
// #6 FIXME: fix, not displaying
missionTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(lastName), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds."
// #7
view.backgroundColor = UIColor(red: 0.585, green: 0.78, blue: 0.188, alpha: 1.0)
}
else
{
greetingLabel.text = "Please enter your password."
agentFailureToAuthenticate()
}
}
else
{
// #8
greetingLabel.text = "Please enter your agent name."
agentFailureToAuthenticate()
}
return rc
}
func agentFailureToAuthenticate()
{
view.backgroundColor = UIColor(red: 0.78, green: 0.188, blue: 0.188, alpha: 1.0)
// TODO: self-destruct sequence
}
}
// 6. The mission briefing textview needs to be populated with the briefing from HQ, but it must also include the last
// name of the agent that logged in. Perhaps you could use the text in the textfield to get the agent's last name.
// How would you inject that last name into the paragraph of the mission briefing?
| cc0-1.0 | c8f2d8e1e4276bc04c7771a9b7051048 | 30.53 | 343 | 0.592005 | 4.979463 | false | false | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/Layer.swift | 2 | 4245 | // 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 QuartzCore
/// A subclass of CALayer that has a rotation property.
public class Layer: CALayer {
static let rotationKey = "rotation"
private var _rotation = 0.0
/// The value of the receiver's current rotation state.
/// This value is cumulative, and can represent values beyong +/- π
public dynamic var rotation: Double {
return _rotation
}
/// Initializes a new Layer
public override init() {
super.init()
}
/// Initializes a new Layer from a specified layer of any other type.
/// - parameter layer: Another CALayer
public override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? Layer {
_rotation = layer._rotation
}
}
/// Initializes a new Layer from data in a given unarchiver.
/// - parameter coder: An unarchiver object.
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
/// Sets a value for a given key.
/// - parameter value: The value for the property identified by key.
/// - parameter key: The name of one of the receiver's properties
public override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
if key == Layer.rotationKey {
_rotation = value as? Double ?? 0.0
}
}
/// This method searches for the given action object of the layer. Actions define dynamic behaviors for a layer. For example, the animatable properties of a layer typically have corresponding action objects to initiate the actual animations. When that property changes, the layer looks for the action object associated with the property name and executes it. You can also associate custom action objects with your layer to implement app-specific actions.
/// - parameter key: The identifier of the action.
/// - returns: the action object assigned to the specified key.
public override func action(forKey key: String) -> CAAction? {
if key == Layer.rotationKey {
let animation = CABasicAnimation(keyPath: key)
animation.configureOptions()
if let layer = presentation() {
animation.fromValue = layer.value(forKey: key)
}
return animation
}
return super.action(forKey: key)
}
/// Returns a Boolean indicating whether changes to the specified key require the layer to be redisplayed.
/// - parameter key: A string that specifies an attribute of the layer.
/// - returns: A Boolean indicating whether changes to the specified key require the layer to be redisplayed.
public override class func needsDisplay(forKey key: String) -> Bool {
if key == Layer.rotationKey {
return true
}
return super.needsDisplay(forKey: key)
}
/// Reloads the content of this layer.
/// Do not call this method directly.
public override func display() {
guard let presentation = presentation() else {
return
}
setValue(presentation._rotation, forKeyPath: "transform.rotation.z")
}
}
| mit | b88a18142bea06d880c35befaded0278 | 42.742268 | 459 | 0.682772 | 4.799774 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/PinFunctionView.swift | 1 | 4381 | //
// Created by Raimundas Sakalauskas on 2019-05-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
protocol PinFunctionViewDelegate: class {
func pinFunctionSelected(pin: DevicePin, function: DevicePinFunction?)
}
class PinFunctionView: UIView {
private let selectedColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
private let unselectedColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15)
@IBOutlet var pinLabel:ParticleLabel!
@IBOutlet var analogReadButton:ParticleCustomButton!
@IBOutlet var analogWriteButton:ParticleCustomButton!
@IBOutlet var digitalReadButton:ParticleCustomButton!
@IBOutlet var digitalWriteButton:ParticleCustomButton!
var pin:DevicePin?
weak var delegate:PinFunctionViewDelegate?
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = false
layer.cornerRadius = 5
layer.applySketchShadow(color: UIColor(rgb: 0x000000), alpha: 0.3, x: 0, y: 2, blur: 4, spread: 0)
pinLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.LargeSize, color: ParticleStyle.PrimaryTextColor)
analogReadButton.layer.borderColor = DevicePinFunction.getColor(function: .analogRead).cgColor
digitalReadButton.layer.borderColor = DevicePinFunction.getColor(function: .digitalRead).cgColor
digitalWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .digitalWrite).cgColor
analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWriteDAC).cgColor
analogReadButton.setTitle(DevicePinFunction.analogRead.getName(), for: .normal)
digitalReadButton.setTitle(DevicePinFunction.digitalRead.getName(), for: .normal)
digitalWriteButton.setTitle(DevicePinFunction.digitalWrite.getName(), for: .normal)
analogWriteButton.setTitle(DevicePinFunction.analogWriteDAC.getName(), for: .normal)
setupButton(analogReadButton)
setupButton(digitalReadButton)
setupButton(digitalWriteButton)
setupButton(analogWriteButton)
}
private func setupButton(_ button: ParticleCustomButton!) {
button.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor)
button.layer.cornerRadius = 3
button.layer.borderWidth = 2
button.backgroundColor = UIColor(rgb: 0xFFFFFF)
}
override func layoutSubviews() {
super.layoutSubviews()
}
func setPin(_ pin: DevicePin?) {
self.pin = pin
guard let pin = self.pin else {
return
}
pinLabel.text = pin.label
analogReadButton.isHidden = true
digitalReadButton.isHidden = true
digitalWriteButton.isHidden = true
analogWriteButton.isHidden = true
if pin.functions.contains(.analogRead) {
analogReadButton.isHidden = false
}
if pin.functions.contains(.digitalRead) {
digitalReadButton.isHidden = false
}
if pin.functions.contains(.digitalWrite) {
digitalWriteButton.isHidden = false
}
if (pin.functions.contains(.analogWritePWM) || pin.functions.contains(.analogWriteDAC)) {
analogWriteButton.isHidden = false
if pin.functions.contains(.analogWriteDAC) {
analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWriteDAC).cgColor
} else {
analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWritePWM).cgColor
}
}
pinLabel.sizeToFit()
}
@IBAction func functionSelected(_ sender: UIButton) {
var function:DevicePinFunction? = nil
if sender == analogReadButton {
function = .analogRead
} else if sender == analogWriteButton {
if self.pin!.functions.contains(.analogWriteDAC) {
function = .analogWriteDAC
} else {
function = .analogWritePWM
}
} else if sender == digitalReadButton {
function = .digitalRead
} else if sender == digitalWriteButton {
function = .digitalWrite
}
self.delegate?.pinFunctionSelected(pin: self.pin!, function: function)
}
}
| apache-2.0 | 197a0634d8954893f77e2e1c764d0e13 | 33.769841 | 128 | 0.677243 | 4.616438 | false | false | false | false |
wagnersouz4/replay | Replay/Replay/Components/Grid/Source/Views/GridTableViewCell.swift | 1 | 2504 | //
// GridTableViewCell.swift
// Replay
//
// Created by Wagner Souza on 28/03/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import UIKit
enum GridOrientation {
case portrait, landscape
}
class GridTableViewCell: UITableViewCell {
fileprivate var collectionView: GridCollectionView!
fileprivate var layout: UICollectionViewFlowLayout!
fileprivate var orientation: GridOrientation
override func awakeFromNib() {
super.awakeFromNib()
}
init(reuseIdentifier: String?, orientation: GridOrientation) {
self.orientation = orientation
super.init(style: .default, reuseIdentifier: reuseIdentifier)
setupCollectionView()
}
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: Collection View
private extension GridTableViewCell {
func setupCollectionView() {
layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
/// Initializing the colletionView
collectionView = GridCollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(GridCollectionViewCell.nib,
forCellWithReuseIdentifier: GridCollectionViewCell.identifier)
/// ColectionView Custom settings
collectionView.backgroundColor = .background
collectionView.isPrefetchingEnabled = true
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.isDirectionalLockEnabled = true
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
contentView.addSubview(collectionView)
}
}
// MARK: Setting collection data source, delegate and section
extension GridTableViewCell {
/// This method will be called in the TableViewController's tableView(_:willDisplay:forRowAt:)
func setCollectionView(dataSource: UICollectionViewDataSource, delegate: UICollectionViewDelegate?, section: Int) {
if collectionView.section == nil {
collectionView.section = section
}
if collectionView.dataSource == nil {
collectionView.dataSource = dataSource
}
if collectionView.delegate == nil {
collectionView.delegate = delegate
}
}
}
| mit | ca6bd422be9604786919459ae576abd2 | 29.901235 | 119 | 0.701958 | 5.93128 | false | false | false | false |
alikaragoz/DaisyChain | Examples/Showcase/Showcase/BrokenChainViewController.swift | 1 | 1383 | //
// BrokenChainViewController.swift
// Showcase
//
// Created by Ali Karagoz on 16/12/15.
// Copyright © 2015 Ali Karagoz. All rights reserved.
//
import Foundation
import UIKit
import DaisyChain
class BrokenChainViewController: UIViewController {
@IBOutlet weak var shape: UIView!
@IBOutlet weak var centerYConstraint: NSLayoutConstraint!
let chain = DaisyChain()
override func viewDidLoad() {
super.viewDidLoad()
shape.layer.cornerRadius = 50.0
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.animate()
}
func animate() {
chain.animateWithDuration(
0.6,
delay: 0.0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 1.2,
options: .CurveEaseInOut,
animations: {
self.centerYConstraint.constant = 150.0
self.view.layoutIfNeeded()
},
completion: nil)
chain.animateWithDuration(
0.6,
delay: 0.0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 1.2,
options: .CurveEaseInOut,
animations: {
self.centerYConstraint.constant = -150.0
self.view.layoutIfNeeded()
},
completion: { _ in
self.animate()
})
}
@IBAction func breakChain(sender: UIButton) {
chain.broken = true
shape.backgroundColor = UIColor.redColor()
}
}
| mit | 79c0190d3720e60d36807119e98db6f6 | 20.59375 | 59 | 0.644718 | 4.305296 | false | false | false | false |
DonMag/ScratchPad | Swift3/scratchy/XC8.playground/Pages/Arrays.xcplaygroundpage/Contents.swift | 1 | 1890 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
var imageList = ["flower", "balloon", "cat", "dog"]
var t = imageList[2]
var i = imageList.count
// two-dimensional array
// should be your Event object... mArray = [[Event]]()
var mArray = [[String]]()
// simulate your allEvents array
var allEvents = ["a 1", "a 2", "a 3", "b 1", "b 2", "c 1", "c 2", "d 1", "d 2", "d 3", "d 4"]
// get first "Day"
// yours will be something like: currentDay = getDateFrom(allEvents[0])
var currentDay = "\(allEvents[0].characters.first)"
// init empty array
// yours will be Event objects... currentEvents = [Event]()
var currentEvents = [String]()
for event in allEvents {
// yours will be something like: thisDay = getDateFrom(event)
var thisDay = "\(event.characters.first)"
if thisDay != currentDay || event == allEvents.last {
mArray.append(currentEvents)
currentDay = thisDay
// reset currentEvents array: currentEvents = [Event]()
currentEvents = [String]()
}
currentEvents.append(event)
}
print(mArray)
mArray = [[String]]()
// get first "Day"
// yours will be something like: currentDay = getDateFrom(allEvents[0])
currentDay = "\(allEvents[0].characters.first)"
// init empty array
// yours will be Event objects... currentEvents = [Event]()
currentEvents = [String]()
for event in allEvents {
// yours will be something like: thisDay = getDateFrom(event)
var thisDay = "\(event.characters.first)"
if thisDay != currentDay {
mArray.append(currentEvents)
currentDay = thisDay
// reset currentEvents array: currentEvents = [Event]()
currentEvents = [String]()
currentEvents.append(event)
} else if event == allEvents.last {
currentEvents.append(event)
mArray.append(currentEvents)
} else {
currentEvents.append(event)
}
}
print(mArray)
| mit | c15204f77083b3c3ef3a547aedb2433d | 19.543478 | 93 | 0.657672 | 3.423913 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Tests/PlatformUIKitTests/Components/PrefillButtons/PrefillButtonsReducerTests.swift | 1 | 3292 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import PlatformUIKit
import BigInt
import Combine
import ComposableArchitecture
import MoneyKit
import XCTest
final class PrefillButtonsReducerTests: XCTestCase {
private var mockMainQueue: ImmediateSchedulerOf<DispatchQueue>!
private var testStore: TestStore<
PrefillButtonsState,
PrefillButtonsState,
PrefillButtonsAction,
PrefillButtonsAction,
PrefillButtonsEnvironment
>!
private let lastPurchase = FiatValue(amount: 900, currency: .USD)
private let maxLimit = FiatValue(amount: 120000, currency: .USD)
override func setUpWithError() throws {
try super.setUpWithError()
mockMainQueue = DispatchQueue.immediate
}
func test_stateValues() {
let state = PrefillButtonsState(
baseValue: FiatValue(amount: 1000, currency: .USD),
maxLimit: maxLimit
)
XCTAssertEqual(state.baseValue, FiatValue(amount: 1000, currency: .USD))
XCTAssertEqual(state.suggestedValues[0], FiatValue(amount: 1000, currency: .USD))
XCTAssertEqual(state.suggestedValues[1], FiatValue(amount: 2000, currency: .USD))
XCTAssertEqual(state.suggestedValues[2], FiatValue(amount: 4000, currency: .USD))
}
func test_stateValues_overMaxLimit() {
let state = PrefillButtonsState(
baseValue: FiatValue(amount: 110000, currency: .USD),
maxLimit: maxLimit
)
XCTAssertEqual(state.baseValue, FiatValue(amount: 110000, currency: .USD))
XCTAssertEqual(state.suggestedValues[0], FiatValue(amount: 110000, currency: .USD))
XCTAssertEqual(state.suggestedValues.count, 1)
}
func test_roundingLastPurchase_after_onAppear() {
testStore = TestStore(
initialState: .init(),
reducer: prefillButtonsReducer,
environment: PrefillButtonsEnvironment(
mainQueue: mockMainQueue.eraseToAnyScheduler(),
lastPurchasePublisher: .just(lastPurchase),
maxLimitPublisher: .just(maxLimit),
onValueSelected: { _ in }
)
)
testStore.send(.onAppear)
let expected = FiatValue(amount: 1000, currency: .USD)
testStore.receive(.updateBaseValue(expected)) { state in
state.baseValue = expected
}
testStore.receive(.updateMaxLimit(maxLimit)) { [maxLimit] state in
state.maxLimit = maxLimit
}
}
func test_select_triggersEnvironmentClosure() {
let e = expectation(description: "Closure should be triggered")
testStore = TestStore(
initialState: .init(),
reducer: prefillButtonsReducer,
environment: PrefillButtonsEnvironment(
lastPurchasePublisher: .just(lastPurchase),
maxLimitPublisher: .just(maxLimit),
onValueSelected: { value in
XCTAssertEqual(value.currency, .USD)
XCTAssertEqual(value.amount, BigInt(123))
e.fulfill()
}
)
)
testStore.send(.select(.init(amount: 123, currency: .USD)))
waitForExpectations(timeout: 1)
}
}
| lgpl-3.0 | 979498a7c24722b7512e559935bdfb36 | 35.977528 | 91 | 0.637496 | 4.90462 | false | true | false | false |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/Source/Sources.Impl/VideoDelegate.swift | 1 | 3944 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.0.2
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
import AdaptiveArpApi
#if os(iOS)
import UIKit
#endif
/**
Interface for Managing the Video operations
Auto-generated implementation of IVideo specification.
*/
public class VideoDelegate : BaseMediaDelegate, IVideo {
/// Logger variable
let logger : ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge()
let loggerTag : String = "VideoDelegate"
#if os(iOS)
/// Application variable
var application:UIApplication? = nil
#endif
/**
Default Constructor.
*/
public override init() {
super.init()
#if os(iOS)
self.application = (AppRegistryBridge.sharedInstance.getPlatformContext().getContext() as! UIApplication)
#endif
}
/**
Play url video stream
@param url of the video
@since ARP1.0
*/
public func playStream(url : String) {
if checkURl(url) {
if (BaseViewController.ViewCurrent.getView() != nil) {
#if os(iOS)
(BaseViewController.ViewCurrent.getView()! as! BaseViewController).showInternalMedia(NSURL(string: url)!, showAnimated: true)
#endif
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The current View Controller has no presented view")
}
}
}
/**
Private method to check if an application is able to open an url
@param url Url to check
@return The result of the operation
*/
private func checkURl(url: String) -> Bool {
// Check if the string is empty
if url.isEmpty {
return false
}
// Check the correct format of the number
if !Utils.validateUrl(url) {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The url: \(url) has an incorrect format")
return false
}
let url: NSURL = NSURL(string: url)!
#if os(iOS)
// Check if it is possible to open the url
if !application!.canOpenURL(url) {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The application cannot open this type of url: \(url)")
return false
}
#endif
#if os(OSX)
// There is no way to check the url validity for OSX
#endif
return true
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 38a22a665692672a0e48c3361669b5dd | 30.03937 | 145 | 0.570015 | 4.921348 | false | false | false | false |
akolov/FlingChallenge | FlingChallengeKit/FlingChallengeKit/DataController.swift | 1 | 4405 | //
// DataController.swift
// FlingChallengeKit
//
// Created by Alexander Kolov on 5/8/16.
// Copyright © 2016 Alexander Kolov. All rights reserved.
//
import Foundation
import CoreData
final public class DataController {
public init() throws {
struct Static {
static var onceToken: dispatch_once_t = 0
}
try dispatch_once_throws(&Static.onceToken) {
try dispatch_sync_main {
try DataController.initializeCoreDataStack()
}
}
}
public static let applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count - 1]
}()
public lazy var mainQueueManagedObjectContext: NSManagedObjectContext = {
return DataController._mainQueueManagedObjectContext
}()
public lazy var privateManagedObjectContext: NSManagedObjectContext = {
return DataController._privateQueueManagedObjectContext
}()
public func withPrivateContext(closure: (NSManagedObjectContext) throws -> Void) throws {
try privateManagedObjectContext.performBlockAndWaitThrowable {
try closure(self.privateManagedObjectContext)
if self.privateManagedObjectContext.hasChanges {
try self.privateManagedObjectContext.save()
}
}
try self.mainQueueManagedObjectContext.performBlockAndWaitThrowable {
if self.mainQueueManagedObjectContext.hasChanges {
try self.mainQueueManagedObjectContext.save()
}
}
}
public func destroyPersistentStore() throws {
try DataController.persistentStoreCoordinator?.destroyPersistentStoreAtURL(
DataController.persistentStoreURL,
withType: NSSQLiteStoreType,
options: DataController.persistentStoreOptions
)
try DataController.persistentStoreCoordinator?.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: nil,
URL: DataController.persistentStoreURL,
options: DataController.persistentStoreOptions
)
}
}
// MARK: Private
private extension DataController {
private static func initializeCoreDataStack() throws {
assert(NSThread.isMainThread(), "\(#function) must be executed on main thread")
guard let bundle = NSBundle(identifier: "com.alexkolov.FlingChallengeKit") else {
throw FlingChallengeError.InitializationError(description: "Could not find framework bundle")
}
guard let modelURL = bundle.URLForResource("Fling", withExtension: "momd") else {
throw FlingChallengeError.InitializationError(description: "Could not find model in main bundle")
}
guard let model = NSManagedObjectModel(contentsOfURL: modelURL) else {
throw FlingChallengeError.InitializationError(description: "Could not load model from URL: \(modelURL)")
}
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType,
configuration: nil,
URL: persistentStoreURL,
options: persistentStoreOptions)
persistentStoreCoordinator = coordinator
let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
_mainQueueManagedObjectContext = context
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = _mainQueueManagedObjectContext
privateContext.mergePolicy = NSMergePolicy(mergeType: .MergeByPropertyObjectTrumpMergePolicyType)
_privateQueueManagedObjectContext = privateContext
}
private static let persistentStoreURL: NSURL = {
return DataController.applicationDocumentsDirectory.URLByAppendingPathComponent(persistentStoreName)
}()
private static let persistentStoreOptions = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
private static let persistentStoreName = "FlingChallenge.sqlite"
private static var managedObjectModel: NSManagedObjectModel?
private static var persistentStoreCoordinator: NSPersistentStoreCoordinator?
private static var _mainQueueManagedObjectContext: NSManagedObjectContext!
private static var _privateQueueManagedObjectContext: NSManagedObjectContext!
}
| mit | 88d57d49b9f05ce46ad6747825c0cfdc | 35.098361 | 110 | 0.750908 | 6.099723 | false | false | false | false |
cwwise/CWWeChat | CWWeChat/ChatModule/CWChatClient/CWChatClientOptions.swift | 2 | 797 | //
// CWChatClientOptions.swift
// CWWeChat
//
// Created by wei chen on 2017/2/14.
// Copyright © 2017年 chenwei. All rights reserved.
//
import Foundation
// 配置信息
public class CWChatClientOptions: NSObject {
public static var `default`: CWChatClientOptions = {
let options = CWChatClientOptions(host: "cwwise.com", domain: "cwwise.com")
return options
}()
/// 端口号
var port: UInt16 = 5222
/// XMPP服务器 ip地址 默认为本地localhost
var host: String
/// XMPP聊天 域
var domain: String
/// 来源 app iOS 安卓等等
var resource: String
init(host: String, domain: String) {
self.host = host
self.domain = domain
self.resource = "ios"
super.init()
}
}
| mit | 6175dbc3db127284de1969763a6276e6 | 20.823529 | 83 | 0.607817 | 3.673267 | false | false | false | false |
Sajjon/Zeus | Zeus/SwiftReflection.swift | 1 | 5108 | //
// SwiftReflection.swift
// SwiftReflection
//
// Created by Cyon Alexander (Ext. Netlight) on 01/09/16.
// Copyright © 2016 com.cyon. All rights reserved.
//
import Foundation
import ObjectiveC.runtime
/*
Please note that the class you are inspecting have to inherit from NSObject.
This tool can find the name and type of properties of type NSObject, e.g. NSString (or just "String" with Swift 3 syntax), NSDate (or just "NSDate" with Swift 3 syntax), NSNumber etc.
It also works with optionals and implicit optionals for said types, e.g. String?, String!, Date!, Date? etc...
This tool can also find name and type of "primitive data types" such as Bool, Int, Int32, _HOWEVER_ it does not work if said primitive have optional type, e.g. Int? <--- DOES NOT WORK
*/
public func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? {
var count = UInt32()
guard let properties = class_copyPropertyList(clazz, &count) else { log.error("Failed to retrieve property list for object of type: '\(clazz)'"); return nil }
var types: Dictionary<String, Any> = [:]
for i in 0..<Int(count) {
guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue }
let type = getTypeOf(property: property)
types[name] = type
}
free(properties)
return types
}
public func getTypesOfProperties(ofObject object: NSObject) -> Dictionary<String, Any>? {
let clazz: NSObject.Type = type(of: object)
return getTypesOfProperties(in: clazz)
}
public func typeOf(property propertyName: String, for object: NSObject) -> Any? {
let type = type(of: object)
return typeOf(property: propertyName, in: type)
}
public func typeOf(property propertyName: String, in clazz: NSObject.Type) -> Any? {
guard let propertyTypes = getTypesOfProperties(in: clazz), let type = propertyTypes[propertyName] else { return nil }
print("Property named: '\(propertyName)' has type: \(type)")
return type
}
public func isProperty(named propertyName: String, ofType targetType: Any, for object: NSObject) -> Bool {
let type = type(of: object)
return isProperty(named: propertyName, ofType: targetType, in: type)
}
public func isProperty(named propertyName: String, ofType targetType: Any, in clazz: NSObject.Type) -> Bool {
let propertyType = typeOf(property: propertyName, in: clazz)
let match = propertyType == targetType
return match
}
fileprivate func ==(rhs: Any, lhs: Any) -> Bool {
var rhsType: String = "\(rhs)".withoutOptional
var lhsType: String = "\(lhs)".withoutOptional
let same = rhsType == lhsType
return same
}
fileprivate func ==(rhs: NSObject.Type, lhs: Any) -> Bool {
let rhsType: String = "\(rhs)".withoutOptional
let lhsType: String = "\(lhs)".withoutOptional
let same = rhsType == lhsType
return same
}
fileprivate func ==(rhs: Any, lhs: NSObject.Type) -> Bool {
let rhsType: String = "\(rhs)".withoutOptional
let lhsType: String = "\(lhs)".withoutOptional
let same = rhsType == lhsType
return same
}
fileprivate func getTypeOf(property: objc_property_t) -> Any {
guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)) else { return Any.self }
let attributes = attributesAsNSString as String
let slices = attributes.components(separatedBy: "\"")
guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) }
let objectClassName = slices[1]
let objectClass = NSClassFromString(objectClassName) as! NSObject.Type
return objectClass
}
fileprivate func getPrimitiveDataType(withAttributes attributes: String) -> Any {
guard let letter = attributes.substring(from: 1, to: 2), let type = primitiveDataTypes[letter] else { return Any.self }
return type
}
fileprivate func getNameOf(property: objc_property_t) -> String? {
guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil }
return name as String
}
fileprivate let primitiveDataTypes: Dictionary<String, Any> = [
"c" : Int8.self,
"s" : Int16.self,
"i" : Int32.self,
"q" : Int.self, //also: Int64, NSInteger, only true on 64 bit platforms
"S" : UInt16.self,
"I" : UInt32.self,
"Q" : UInt.self, //also UInt64, only true on 64 bit platforms
"B" : Bool.self,
"d" : Double.self,
"f" : Float.self,
"{" : Decimal.self
]
private extension String {
func substring(from fromIndex: Int, to toIndex: Int) -> String? {
let substring = self[self.index(self.startIndex, offsetBy: fromIndex)..<self.index(self.startIndex, offsetBy: toIndex)]
return substring
}
/// Extracts "NSDate" from the string "Optional(NSDate)"
var withoutOptional: String {
guard self.contains("Optional(") && self.contains(")") else { return self }
let afterOpeningParenthesis = self.components(separatedBy: "(")[1]
let wihtoutOptional = afterOpeningParenthesis.components(separatedBy: ")")[0]
return wihtoutOptional
}
}
| apache-2.0 | df7dce25b446e7a0e8bb9062479d2542 | 37.398496 | 184 | 0.694145 | 3.931486 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/CloudBackup/SelectBackupView.swift | 1 | 3933 | //
// SelectBackupView.swift
// breadwallet
//
// Created by Adrian Corscadden on 2020-07-30.
// Copyright © 2020 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import SwiftUI
enum SelectBackupError: Error {
case didCancel
}
@available(iOS 13.6, *)
typealias SelectBackupResult = Result<CloudBackup, Error>
@available(iOS 13.6, *)
struct SelectBackupView: View {
let backups: [CloudBackup]
let callback: (SelectBackupResult) -> Void
@SwiftUI.State private var selectedBackup: CloudBackup?
var body: some View {
ZStack {
Rectangle()
.fill(Color(Theme.primaryBackground))
VStack {
Text(S.CloudBackup.selectTitle)
.foregroundColor(Color(Theme.primaryText))
.lineLimit(nil)
.font(Font(Theme.h2Title))
ForEach(0..<backups.count) { i in
BackupCell(backup: self.backups[i],
isOn: self.binding(for: i))
.padding(4.0)
}
self.okButton()
}
}.edgesIgnoringSafeArea(.all)
.navigationBarItems(trailing: EmptyView())
}
private func okButton() -> some View {
Button(action: {
self.callback(.success(self.selectedBackup!))
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 4.0)
.fill(Color(UIColor.primaryButton))
.opacity(self.selectedBackup == nil ? 0.3 : 1.0)
Text(S.Button.continueAction)
.foregroundColor(Color(Theme.primaryText))
.font(Font(Theme.h3Title))
}
})
.frame(height: 44.0)
.cornerRadius(4.0)
.disabled(self.selectedBackup == nil)
.padding(EdgeInsets(top: 8.0, leading: 32.0, bottom: 32.0, trailing: 32.0))
}
private func binding(for index: Int) -> Binding<Bool> {
Binding<Bool>(
get: {
guard let selectedBackup = self.selectedBackup else { return false }
return self.backups[index].identifier == selectedBackup.identifier },
set: { if $0 { self.selectedBackup = self.backups[index] } }
)
}
}
@available(iOS 13.6, *)
struct BackupCell: View {
let backup: CloudBackup
@SwiftUI.Binding var isOn: Bool
private let gradient = Gradient(colors: [Color(UIColor.gradientStart), Color(UIColor.gradientEnd)])
var body: some View {
HStack {
RadioButton(isOn: $isOn)
.frame(width: 44.0, height: 44.0)
VStack(alignment: .leading) {
Text(dateString)
.foregroundColor(Color(Theme.primaryText))
.font(Font(Theme.body1))
.padding(EdgeInsets(top: 8.0, leading: 8.0, bottom: 0.0, trailing: 8.0))
Text("\(backup.deviceName)")
.foregroundColor(Color(Theme.secondaryText))
.font(Font(Theme.body1))
.padding(EdgeInsets(top: 0.0, leading: 8.0, bottom: 8.0, trailing: 8.0))
}
}
}
var dateString: String {
let df = DateFormatter()
df.dateFormat = "MMM d yyyy HH:mm:ss"
return "\(df.string(from: backup.createTime))"
}
}
@available(iOS 13.6, *)
struct RestoreCloudBackupView_Previews: PreviewProvider {
static var previews: some View {
SelectBackupView(backups: [
CloudBackup(phrase: "this is a phrase", identifier: "key", pin: "12345"),
CloudBackup(phrase: "this is another phrase", identifier: "key", pin: "12345"),
CloudBackup(phrase: "this is yet another phrase", identifier: "key", pin: "12345")
], callback: {_ in })
}
}
| mit | 575e39cf6616ae9717c9a9cb187c8700 | 32.606838 | 103 | 0.554934 | 4.255411 | false | false | false | false |
david-mcqueen/Pulser | Heart Rate Monitor - Audio/Classes/UserSettings.swift | 1 | 2288 | //
// UserSettings.swift
// Heart Rate Monitor - Audio
//
// Created by DavidMcQueen on 28/03/2015.
// Copyright (c) 2015 David McQueen. All rights reserved.
//
import Foundation
class UserSettings {
var AnnounceAudio: Bool;
var AnnounceAudioZoneChange: Bool;
var AudioIntervalMinutes: Double;
var AudioIntervalSeconds: Double;
var SaveHealthkit: Bool;
var HealthkitIntervalMinutes: Double;
var UserZones: [Zone];
var CurrentZone: HeartRateZone;
var AnnounceAudioShort: Bool;
init(){
//Default user settings
AnnounceAudio = true;
AnnounceAudioZoneChange = true;
AudioIntervalMinutes = 1.0;
AudioIntervalSeconds = 0.0;
SaveHealthkit = false;
HealthkitIntervalMinutes = 1.0;
UserZones = [];
CurrentZone = HeartRateZone.Rest;
AnnounceAudioShort = false;
}
func shouldAnnounceAudio()->Bool{
return AnnounceAudio && AnnounceAudioZoneChange;
}
func getAudioIntervalMinutesFloat()->Float{
return convertDoubleToFloat(self.AudioIntervalMinutes);
}
func getAudioIntervalSecondsFloat()->Float {
return convertDoubleToFloat(self.AudioIntervalSeconds);
}
func getHealthkitIntervalasFloat()->Float{
return convertDoubleToFloat(self.HealthkitIntervalMinutes);
}
private func convertDoubleToFloat(input: Double)->Float{
return Float(input);
}
func getAudioIntervalSeconds()->Double{
return convertMinuteToSeconds(self.AudioIntervalMinutes) + self.AudioIntervalSeconds
}
func getHealthkitIntervalSeconds()->Double{
return convertMinuteToSeconds(self.HealthkitIntervalMinutes)
}
func allZonesToString()->String{
var zonesAsString: String = "";
for zone in UserZones{
zonesAsString += "\(singleZoneToString(zone))\n"
}
return zonesAsString;
}
private func singleZoneToString(inputZone: Zone)->String{
return "Zone \(inputZone.getZoneType().rawValue) - Min: \(inputZone.Lower) - Max: \(inputZone.Upper)"
}
private func convertMinuteToSeconds(minutes: Double)->Double{
return minutes * 60;
}
} | gpl-3.0 | 05dd3f41dc92298c8cca810e18573a71 | 26.25 | 109 | 0.653409 | 4.495088 | false | false | false | false |
rallahaseh/RALocalization | Example/RALocalization/ViewController.swift | 1 | 2901 | //
// ViewController.swift
// RALocalization
//
// Created by rallahaseh on 10/17/2017.
// Copyright (c) 2017 rallahaseh. All rights reserved.
//
import UIKit
import RALocalization
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// self.button.titleLabel?.text = NSLocalizedString("changeLanguage", comment: "Change Language")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeLanguage(_ sender: UIButton) {
var transition: UIViewAnimationOptions = .transitionFlipFromLeft
let actionSheet = UIAlertController(title: nil, message: "Switch Language", preferredStyle: UIAlertControllerStyle.actionSheet)
let availableLanguages = ["English", "אנגלית", "العربية"]
for language in availableLanguages {
let displayName = language
let languageAction = UIAlertAction(title: displayName, style: .default, handler: {
(alert: UIAlertAction!) -> Void in
if language == "English" {
RALanguage.setLanguage(language: .english)
transition = .transitionFlipFromRight
UIView.appearance().semanticContentAttribute = .forceLeftToRight
} else if language == "العربية" {
RALanguage.setLanguage(language: .arabic)
UIView.appearance().semanticContentAttribute = .forceRightToLeft
} else {
transition = .transitionCurlUp
RALanguage.setLanguage(language: .hebrew)
UIView.appearance().semanticContentAttribute = .forceRightToLeft
}
let rootVC: UIWindow = ((UIApplication.shared.delegate?.window)!)!
rootVC.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "root")
let mainWindow = (UIApplication.shared.delegate?.window!)!
mainWindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8)
UIView.transition(with: mainWindow, duration: 0.55001, options: transition, animations: { () -> Void in
}) { (finished) -> Void in}
})
actionSheet.addAction(languageAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {
(alert: UIAlertAction) -> Void in
})
actionSheet.addAction(cancelAction)
self.present(actionSheet, animated: true, completion: nil)
}
}
| mit | 5b4c0dff049451ed1aa01083a634b4e6 | 42.651515 | 135 | 0.630684 | 5.190991 | false | false | false | false |
LeoMobileDeveloper/PullToRefreshKit | Demo/Demo/DianpingRefreshHeader.swift | 1 | 2049 | //
// DianpingRefreshHeader.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/7/15.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
import PullToRefreshKit
class DianpingRefreshHeader:UIView,RefreshableHeader{
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - RefreshableHeader -
func heightForHeader() -> CGFloat {
return 60.0
}
//监听百分比变化
func percentUpdateDuringScrolling(_ percent:CGFloat){
imageView.isHidden = (percent == 0)
let adjustPercent = max(min(1.0, percent),0.0)
let scale = 0.2 + (1.0 - 0.2) * adjustPercent;
imageView.transform = CGAffineTransform(scaleX: scale, y: scale)
let mappedIndex = Int(adjustPercent * 60)
let imageName = "dropdown_anim__000\(mappedIndex)"
let image = UIImage(named: imageName)
imageView.image = image
}
//松手即将刷新的状态
func didBeginRefreshingState(){
let images = ["dropdown_loading_01","dropdown_loading_02","dropdown_loading_03"].map { (name) -> UIImage in
return UIImage(named:name)!
}
imageView.animationImages = images
imageView.animationDuration = Double(images.count) * 0.15
imageView.startAnimating()
}
//刷新结束,将要隐藏header
func didBeginHideAnimation(_ result:RefreshResult){}
//刷新结束,完全隐藏header
func didCompleteHideAnimation(_ result:RefreshResult){
imageView.animationImages = nil
imageView.stopAnimating()
imageView.isHidden = true
}
}
| mit | 7c375828ced8efb48da279698c8a205a | 32.525424 | 115 | 0.650657 | 4.190678 | false | false | false | false |
powerytg/Accented | Accented/UI/Home/Themes/Card/Renderers/StreamCardPhotoCell.swift | 1 | 5819 | //
// StreamCardPhotoCell.swift
// Accented
//
// Created by You, Tiangong on 8/25/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class StreamCardPhotoCell: StreamPhotoCellBaseCollectionViewCell {
private var titleLabel = UILabel()
private var descLabel = UILabel()
private var subtitleLabel = UILabel()
private var footerView = UIImageView()
private var cardBackgroundLayer = CALayer()
private var currentTheme : AppTheme {
return ThemeManager.sharedInstance.currentTheme
}
override func initialize() {
// Background (only available in light card theme)
contentView.layer.insertSublayer(cardBackgroundLayer, at: 0)
cardBackgroundLayer.backgroundColor = UIColor.white.cgColor
cardBackgroundLayer.shadowColor = UIColor.black.cgColor
cardBackgroundLayer.shadowOpacity = 0.12
cardBackgroundLayer.cornerRadius = 2
cardBackgroundLayer.shadowRadius = 6
// Title
titleLabel.textColor = currentTheme.titleTextColor
titleLabel.font = StreamCardLayoutSpec.titleFont
titleLabel.numberOfLines = StreamCardLayoutSpec.titleLabelLineCount
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byTruncatingMiddle
contentView.addSubview(titleLabel)
// Subtitle
subtitleLabel.textColor = UIColor(red: 147 / 255.0, green: 147 / 255.0, blue: 147 / 255.0, alpha: 1.0)
subtitleLabel.font = StreamCardLayoutSpec.subtitleFont
subtitleLabel.numberOfLines = StreamCardLayoutSpec.subtitleLineCount
subtitleLabel.textAlignment = .center
subtitleLabel.lineBreakMode = .byTruncatingMiddle
contentView.addSubview(subtitleLabel)
// Photo
renderer.clipsToBounds = true
renderer.contentMode = .scaleAspectFill
contentView.addSubview(renderer)
// Descriptions
descLabel.textColor = currentTheme.standardTextColor
descLabel.font = ThemeManager.sharedInstance.currentTheme.descFont
descLabel.numberOfLines = StreamCardLayoutSpec.descLineCount
descLabel.textAlignment = .center
descLabel.lineBreakMode = .byTruncatingTail
contentView.addSubview(descLabel)
// Bottom line and footer
if ThemeManager.sharedInstance.currentTheme is DarkCardTheme {
footerView.image = UIImage(named: "DarkJournalFooter")
} else {
footerView.image = UIImage(named: "LightJournalFooter")
}
footerView.sizeToFit()
contentView.addSubview(footerView)
}
override func layoutSubviews() {
super.layoutSubviews()
if photo == nil {
return
}
if bounds.width == 0 || bounds.height == 0 {
isHidden = true
return
}
// Content view
isHidden = false
contentView.frame = bounds
let photoModel = photo!
let w = self.contentView.bounds.width
var nextY : CGFloat = StreamCardLayoutSpec.topPadding
// Background
if currentTheme is LightCardTheme {
cardBackgroundLayer.isHidden = false
cardBackgroundLayer.frame = contentView.bounds
} else {
cardBackgroundLayer.isHidden = true
}
// Photo
let aspectRatio = photoModel.width / photoModel.height
let desiredHeight = w / aspectRatio
var f = renderer.frame
f.origin.x = StreamCardLayoutSpec.photoLeftPadding
f.origin.y = nextY
f.size.width = w - StreamCardLayoutSpec.photoLeftPadding - StreamCardLayoutSpec.photoRightPadding
f.size.height = min(desiredHeight, StreamCardLayoutSpec.maxPhotoHeight)
renderer.frame = f
renderer.photo = photoModel
nextY += f.height + StreamCardLayoutSpec.photoVPadding
// Title label
titleLabel.textColor = currentTheme.cardTitleColor
titleLabel.text = photoModel.title
layoutLabel(titleLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.titleHPadding)
nextY += titleLabel.frame.height + StreamCardLayoutSpec.titleVPadding
// Subtitle label
subtitleLabel.text = photoModel.user.firstName
layoutLabel(subtitleLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.subtitleHPadding)
nextY += subtitleLabel.frame.height + StreamCardLayoutSpec.photoVPadding
// Description
descLabel.textColor = currentTheme.cardDescColor
if let descData = photoModel.desc?.data(using: String.Encoding.utf8) {
do {
let descText = try NSAttributedString(data: descData, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
descLabel.text = descText.string
} catch _ {
descLabel.text = nil
}
} else {
descLabel.text = nil
}
layoutLabel(descLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.descHPadding)
// Footer
nextY = descLabel.frame.maxY + StreamCardLayoutSpec.footerTopPadding
f = footerView.frame
f.origin.x = w / 2 - f.width / 2
f.origin.y = nextY
footerView.frame = f
}
private func layoutLabel(_ label : UILabel, width : CGFloat, originY : CGFloat, padding : CGFloat) {
var f = label.frame
f.origin.y = originY
f.size.width = width - padding * 2
label.frame = f
label.sizeToFit()
f = label.frame
f.origin.x = width / 2 - f.width / 2
label.frame = f
}
}
| mit | c4e51c31a7418dfc0641269a607aa269 | 36.294872 | 163 | 0.642661 | 5.274705 | false | false | false | false |
LawrenceHan/iOS-project-playground | Swift_A_Big_Nerd_Ranch_Guide/MonsterTown property/MonsterTown/main.swift | 1 | 928 | //
// main.swift
// MonsterTown
//
// Created by Hanguang on 3/1/16.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
var myTown = Town(region: "West", population: 0, stoplights: 6)
myTown?.printTownDescription()
let ts = myTown?.townSize
print(ts)
myTown?.changePopulation(100000)
print("Size: \(myTown?.townSize); population: \(myTown?.population)")
var fredTheZombie: Zombie? = Zombie(limp: false, fallingApart: false, town: myTown, monsterName: "Fred")
fredTheZombie?.terrorizeTown()
fredTheZombie?.changeName("Fred the Zombie", walksWithLimp: false)
var convenientZombie = Zombie(limp: true, fallingApart: false)
fredTheZombie?.town?.printTownDescription()
print("Victim pool: \(fredTheZombie?.victimPool)")
fredTheZombie?.victimPool = 500
print("Victim pool: \(fredTheZombie?.victimPool)")
print(Zombie.spookyNoise)
if Zombie.isTeerifying {
print("Run away!")
}
fredTheZombie = nil | mit | 6cbc8ae6c73590b69829cdc3c4013850 | 24.777778 | 104 | 0.743258 | 3.207612 | false | false | false | false |
BrantSteven/SinaProject | BSweibo/BSweibo/class/Tools/NetWorkingTool.swift | 1 | 2144 | //
// NetWorkingTool.swift
// AfnetWorking
//
// Created by 上海旅徒电子商务有限公司 on 16/9/20.
// Copyright © 2016年 白霜. All rights reserved.
//
import UIKit
import AFNetworking
class NetWorkingTool: AFHTTPSessionManager {
enum requestType:Int {
case GET
case POST
}
// swift 单例 let 线程安全
// static let shareInstance : NetWorkingTool = NetWorkingTool()
//为了添加text/html的数据格式 可以使用闭包创建对象
static let shareInstance : NetWorkingTool = {
let tool = NetWorkingTool(baseURL: NSURL(string: RequestUrl) as URL?)
//(重设)设置AFN能够接收的数据类型
// tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/html","text/plain") as? Set<String>
//(在原有的基础上)添加AFN能够接收的数据类型
tool.responseSerializer.acceptableContentTypes?.insert("text/html")
tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tool
}()
}
//MARK: - 封装请求方法
//Json序列化不支持格式 text/html
extension NetWorkingTool{
func request (requestType:requestType,urlString:String,parameters:[String:AnyObject],finished:@escaping (_ requestResult:AnyObject?,_ requestError:Error?)->()){
//1.定义一个成功的回调
let successCallBack = { (tark:URLSessionDataTask, result:Any?) in
bsLog(message: result)
finished(result as AnyObject?, nil)
}
//2.定义失败的回调
let failureCallBack = { (task:URLSessionDataTask?, error:Error) in
bsLog(message: error)
finished(nil, error as Error?)
}
if requestType == .GET {
get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}else{
post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
}
}
| mit | ca5977e5ab85a3ca92f2d2c9b6271e6b | 37.74 | 166 | 0.641198 | 4.2949 | false | false | false | false |
kaich/CKAlertView | CKAlertView/Classes/Core/CKAlertView+MajorAction.swift | 1 | 5041 | //
// CKAlertView+MajorAction.swift
// Pods
//
// Created by mac on 16/10/12.
//
//
import Foundation
public extension CKAlertView {
/// 显示突出主功能按钮的弹出框(主功能按钮长,取消按钮和其他按钮居其下方)
///
/// - parameter alertTitle: 标题
/// - parameter alertMessages: 主体,$代表段落的结尾
/// - parameter cancelButtonTitle: 取消按钮标题
/// - parameter majorButtonTitle: 主体按钮标题
/// - parameter anotherButtonTitle: 其他按钮标题
/// - parameter completeBlock: 点击按钮后的回调
public convenience init(title alertTitle :CKAlertViewStringable, message alertMessages :[CKAlertViewStringable]?, cancelButtonTitle :CKAlertViewStringable, majorButtonTitle :CKAlertViewStringable, anotherButtonTitle :CKAlertViewStringable, completeBlock :(((Int) -> Void))? = nil) {
self.init(nibName: nil, bundle: nil)
dismissCompleteBlock = completeBlock
let componentMaker = CKAlertViewComponentMajorActionMaker()
componentMaker.alertView = self
componentMaker.alertTitle = alertTitle
componentMaker.alertMessages = alertMessages
componentMaker.cancelButtonTitle = cancelButtonTitle
componentMaker.otherButtonTitles = [majorButtonTitle,anotherButtonTitle]
componentMaker.indentationPatternWidth = indentationPatternWidth
installComponentMaker(maker: componentMaker)
}
}
class CKAlertViewBottomSplitLineHeaderView : CKAlertViewHeaderView {
override func setup() {
super.setup()
textFont = UIFont.systemFont(ofSize: 15)
}
override func makeLayout() {
super.makeLayout()
let splitLineView = UIView()
splitLineView.backgroundColor = config().splitLineColor
addSubview(splitLineView)
splitLineView.snp.makeConstraints { (make) in
make.bottom.equalTo(self).offset(-20)
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
make.height.equalTo(config().splitLineWidth)
}
if let titleLabel = subviews.first {
titleLabel.snp.remakeConstraints({ (make) in
make.top.equalTo(self).offset(20)
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
make.bottom.equalTo(splitLineView).offset(-20)
})
}
}
}
class CKAlertViewMajorActionFooterView : CKAlertViewFooterView {
override func setup() {
super.setup()
textColor = HexColor(0x666666,1)
cancelButtonTitleColor = HexColor(0x666666,1)
}
override func makeFooterTopHSplitLine() -> UIView? {
return nil
}
override func layoutMultiButtons () {
if otherButtons.count == 2 {
let majorButton = otherButtons.first
let anotherButton = otherButtons[1]
majorButton?.backgroundColor = HexColor(0x49bc1e,1)
majorButton?.layer.cornerRadius = 3
majorButton?.layer.masksToBounds = true
majorButton?.setTitleColor(UIColor.white, for: .normal)
majorButton?.snp.makeConstraints({ (make) in
make.top.equalTo(self)
make.left.equalTo(self).offset(20)
make.height.equalTo(36)
make.right.equalTo(self).offset(-20)
})
cancelButton.snp.makeConstraints { (make) in
make.top.equalTo(majorButton!.snp.bottom).offset(20)
make.left.equalTo(self).offset(20)
make.height.equalTo(36)
make.bottom.equalTo(self).offset(-20)
}
anotherButton.snp.makeConstraints { (make) in
make.left.equalTo(cancelButton.snp.right).offset(20)
make.top.bottom.equalTo(cancelButton)
make.width.height.equalTo(cancelButton)
make.right.equalTo(self).offset(-20)
}
}
}
}
class CKAlertViewComponentMajorActionMaker :CKAlertViewComponentMaker {
override func makeHeader() -> CKAlertViewComponent? {
let headerView = CKAlertViewBottomSplitLineHeaderView()
headerView.alertTitle = alertTitle
headerView.alertTitle = alertTitle
return headerView
}
override func makeBody() -> CKAlertViewComponent? {
let bodyView = super.makeBody()
bodyView?.textColor = HexColor(0x666666,1)
return bodyView
}
override func makeFooter() -> CKAlertViewComponent? {
let footerView = CKAlertViewMajorActionFooterView()
footerView.delegate = delegate
footerView.cancelButtonTitle = cancelButtonTitle
footerView.otherButtonTitles = otherButtonTitles
return footerView
}
}
| mit | 72f171cfeef19740e74e3774bcea2771 | 31.892617 | 286 | 0.618853 | 4.847676 | false | false | false | false |
STShenZhaoliang/STKitSwift | STKitSwift/STAreaPickerView.swift | 1 | 7324 | //
// STAreaPickerView.swift
// STKitSwiftDemo
//
// Created by mac on 2019/7/8.
// Copyright © 2019 沈兆良. All rights reserved.
//
import UIKit
import SnapKit
struct STChinaRegionsModel: Codable {
var code:String?
var name:String?
var children:[STChinaRegionsModel]?
}
public class STAreaPickerView: UIButton {
// MARK: 1.lift cycle
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(hidden), for: .touchUpInside)
provinceRegion = models.first
cityModels = provinceRegion?.children ?? []
cityRegion = cityModels.first
areaModels = cityRegion?.children ?? []
areaRegion = areaModels.first
contentView.snp.makeConstraints { (maker) in
maker.left.right.equalToSuperview()
maker.height.equalTo(260)
maker.bottom.equalTo(260)
}
pickerView.snp.makeConstraints { (maker) in
maker.left.right.bottom.equalToSuperview()
maker.height.equalTo(216)
}
topView.snp.makeConstraints { (maker) in
maker.left.right.equalToSuperview()
maker.height.equalTo(44)
maker.bottom.equalTo(pickerView.snp.top)
}
buttonCancel.snp.makeConstraints { (maker) in
maker.left.top.bottom.equalToSuperview()
maker.width.equalTo(66)
}
buttonOK.snp.makeConstraints { (maker) in
maker.right.top.bottom.equalToSuperview()
maker.width.equalTo(66)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: 2.private methods
public class func show(inView view:UIView, selectedBlock block:((String?, String?, String?, String?, String?, String?) -> ())?){
let pickerView = STAreaPickerView()
view.addSubview(pickerView)
pickerView.snp.makeConstraints { (maker) in
maker.edges.equalToSuperview()
}
pickerView.selectedBlock = block
pickerView.show()
}
@objc func show(){
UIView.animate(withDuration: 0.3) {
self.contentView.snp.updateConstraints({ (maker) in
maker.bottom.equalTo(0)
})
}
}
@objc func hidden(){
contentView.snp.updateConstraints({ (maker) in
maker.bottom.equalTo(260)
})
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
}) { (finish) in
self.removeFromSuperview()
}
}
// MARK: 3.event response
@objc func actionOK(){
selectedBlock?(provinceRegion?.name, provinceRegion?.code, cityRegion?.name, cityRegion?.code, areaRegion?.name, areaRegion?.code)
hidden()
}
// MARK: 4.interface
private lazy var models: [STChinaRegionsModel] = {
let models:[STChinaRegionsModel]? = try? JSONDecoder().decode([STChinaRegionsModel].self, from: Data.st_data(named: "pca-code"))
return models ?? []
}()
private var cityModels:[STChinaRegionsModel] = []
private var areaModels:[STChinaRegionsModel] = []
private var provinceRegion:STChinaRegionsModel?
private var cityRegion:STChinaRegionsModel?
private var areaRegion:STChinaRegionsModel?
private var selectedBlock:((String?, String?, String?, String?, String?, String?) -> ())?
// MARK: 5.getter
private lazy var contentView: UIView = {
let contentView = UIView()
contentView.backgroundColor = .white
addSubview(contentView)
return contentView
}()
private lazy var pickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.backgroundColor = .white
pickerView.dataSource = self
pickerView.delegate = self
contentView.addSubview(pickerView)
return pickerView
}()
private lazy var topView: UIView = {
let topView = UIView()
topView.backgroundColor = UIColor.init(red: 245.0/255, green: 245.0/255, blue: 245.0/255, alpha: 1)
contentView.addSubview(topView)
return topView
}()
private lazy var buttonCancel: UIButton = {
let button = UIButton()
button.setTitle("取消", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
button.setTitleColor( UIColor.init(red: 0/255, green: 122.0/255, blue: 255.0/255, alpha: 1), for: .normal)
button.addTarget(self, action: #selector(hidden), for: .touchUpInside)
topView.addSubview(button)
return button
}()
private lazy var buttonOK: UIButton = {
let button = UIButton()
button.setTitle("完成", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
button.setTitleColor( UIColor.init(red: 0/255, green: 122.0/255, blue: 255.0/255, alpha: 1), for: .normal)
button.addTarget(self, action: #selector(actionOK), for: .touchUpInside)
topView.addSubview(button)
return button
}()
}
extension STAreaPickerView: UIPickerViewDataSource{
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return models.count
case 1:
return cityModels.count
default:
return areaModels.count
}
}
}
extension STAreaPickerView: UIPickerViewDelegate{
public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var text = ""
switch component {
case 0:
text = models[row].name ?? ""
case 1:
text = cityModels[row].name ?? ""
default:
text = areaModels[row].name ?? ""
}
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 19)
label.adjustsFontSizeToFitWidth = true
label.text = text
return label
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
provinceRegion = models[row]
cityModels = provinceRegion?.children ?? []
cityRegion = cityModels.first
areaModels = cityRegion?.children ?? []
areaRegion = areaModels.first
pickerView.reloadComponent(1)
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 1, animated: true)
pickerView.selectRow(0, inComponent: 2, animated: true)
case 1:
cityRegion = cityModels[row]
areaModels = cityRegion?.children ?? []
areaRegion = areaModels.first
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 2, animated: true)
default:
areaRegion = areaModels[row]
break
}
}
}
| mit | 9f0898a4a581a59265734cf9419b8cf5 | 31.923423 | 139 | 0.600766 | 4.673274 | false | false | false | false |
zhangjk4859/animal-plant_pool | animal-plant_pool/animal-plant_pool/其他/Controller/LoginVC.swift | 1 | 1453 | //
// LoginVC.swift
// animal-plant_pool
//
// Created by 张俊凯 on 2017/2/14.
// Copyright © 2017年 张俊凯. All rights reserved.
//
import UIKit
class LoginVC: UIViewController{
var backgroundImageView:UIImageView?
var tableView : UITableView?
override func viewDidLoad() {
super.viewDidLoad()
//首先添加一个imageView
backgroundImageView = UIImageView(image: UIImage(named: "background"))
view.backgroundColor = UIColor.white
view.addSubview(backgroundImageView!)
//颜色渐变
//添加三个按钮,宽度平分成六份
let width = view.width / 6
let height = width + 30
var names = ["手机登录","微信登录","QQ登录"]
var imageNames = ["login_mobile","login_weixin","login_QQ"]
for index in 0 ..< 3 {
let btn = JKVerticalButton.init(type: UIButtonType.custom)
view.addSubview(btn)
btn.frame = CGRect(x: CGFloat(Float(index)) * width * 2 + width * 0.5, y: backgroundImageView!.frame.maxY + width, width: width, height: height)
btn.setTitle(names[index], for: UIControlState.normal)
btn.titleLabel?.adjustsFontSizeToFitWidth = true
btn.setTitleColor(UIColor.black, for: .normal)
btn.setImage(UIImage(named:imageNames[index]), for: UIControlState.normal)
}
}
}
| mit | f4b87f56cb2aa54fecd2de9f39a4ad83 | 27.583333 | 156 | 0.60277 | 4.355556 | false | false | false | false |
nikita-leonov/tispr-card-stack | TisprCardStackExample/TisprCardStackExample/TisprCardStackDemoViewCell.swift | 2 | 1969 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// TisprCardStackDemoViewCell.swift
// TisprCardStackExample
//
// Created by Andrei Pitsko on 7/12/15.
// Copyright (c) 2015 BuddyHopp Inc. All rights reserved.
//
import UIKit
import TisprCardStack
class TisprCardStackDemoViewCell: TisprCardStackViewCell {
@IBOutlet weak var text: UILabel!
@IBOutlet weak var voteSmile: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 12
clipsToBounds = false
}
override var center: CGPoint {
didSet {
updateSmileVote()
}
}
override internal func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) {
super.applyLayoutAttributes(layoutAttributes)
updateSmileVote()
}
func updateSmileVote() {
let rotation = atan2(transform.b, transform.a)
if rotation == 0 {
voteSmile.hidden = true
} else {
voteSmile.hidden = false
let voteSmileImageName = (rotation > 0) ? "smile_face" : "rotten_face"
voteSmile.image = UIImage(named: voteSmileImageName)
}
}
} | apache-2.0 | 140249581520df0dfc9195ed8f0c7cbf | 28.402985 | 103 | 0.683596 | 4.55787 | false | false | false | false |
ZoranPandovski/al-go-rithms | sort/radix_sort/swift/radixSort.swift | 1 | 530 | extension Array where Element == Int {
public mutating func radixSort() {
let base = 10
var done = false
var digits = 1
while !done {
done = true
var buckets: [[Int]] = .init(repeating: [], count: base)
forEach {
number in
let remainingPart = number / digits
let digit = remainingPart % base
buckets[digit].append(number)
if remainingPart > 0 {
done = false
}
}
digits *= base
self = buckets.flatMap { $0 }
}
}
} | cc0-1.0 | 6be83f66d9d122530ebf575335d30de6 | 23.136364 | 62 | 0.537736 | 4.308943 | false | false | false | false |
ledwards/ios-flicks | Flicks/AppDelegate.swift | 1 | 3450 | //
// AppDelegate.swift
// Flicks
//
// Created by Lee Edwards on 2/1/16.
// Copyright © 2016 Lee Edwards. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing")
let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 12171a433b59e424bcf7c526b3bf7721 | 50.477612 | 285 | 0.753842 | 6.082892 | false | false | false | false |
cocoascientist/Playgrounds | MultiThreading.playground/Contents.swift | 1 | 1927 | //: # Multithreading with GCD
import Cocoa
import XCPlayground
//: First we define a function do perform some simulated work. In the real world, this could be parsing a complex JSON file, compressing a file to disk, or some other long running task.
func countTo(limit: Int) -> Int {
var total = 0
for _ in 1...limit {
total += 1
}
return total
}
//: Next we grab a reference to a global dispatch queue for running tasks.
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//: A block is function that has no parmaters and returns nothing. In GCD terms, this is defined as the `dispatch_block_t` type. Blocks are typically declaring inline when a call to GCD is made.
let block: dispatch_block_t = { () -> Void in
countTo(100)
print("done with single block")
}
dispatch_async(queue, block)
//: Multiple tasks be arranged together in a group. This makes it possible to wait for the result of multiple asynchronous tasks.
let group = dispatch_group_create()
dispatch_group_enter(group)
dispatch_group_enter(group)
dispatch_async(queue, { () -> Void in
countTo(10)
print("finished first grouped task")
dispatch_group_leave(group)
})
dispatch_async(queue, { () -> Void in
countTo(20)
print("finished second grouped task")
dispatch_group_leave(group)
})
dispatch_group_notify(group, queue) { () -> Void in
print("finished ALL grouped tasks")
}
//: Queues can have differnt priority levels.
let high = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
let low = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
let background = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
//: The playground needs to continue to run indefinitely. It doesn't matter if we put this statement at the top or bottom of the playground. I prefer it at the bottom.
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | 80f5b66d38ace1cae6414c2e2732e71b | 31.116667 | 194 | 0.727556 | 3.8083 | false | false | false | false |
cschlessinger/dbc-civichack-artistnonprofit | iOS/DevBootcampHackathon/DevBootcampHackathon/ViewController.swift | 1 | 2229 | //
// ViewController.swift
// DevBootcampHackathon
//
// Created by Lucas Farah on 1/23/16.
// Copyright © 2016 Lucas Farah. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ImagePickerDelegate {
var arrCat = ["Senior","Homeless","Children","Animals"]
var arrCatNum = ["109","230","59","90"]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource
{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrCat.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell!
if !(cell != nil)
{
cell = TableViewCell(style:.Default, reuseIdentifier: "cell")
}
let imgvName = arrCat[indexPath.row] + ".jpg"
// setup cell without force unwrapping it
cell.lblName.text = arrCat[indexPath.row]
cell.lblNumber.text = arrCatNum[indexPath.row]
cell.imgvCat.image = UIImage(named: imgvName)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
self.performSegueWithIdentifier("selected", sender: self)
}
func wrapperDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func doneButtonDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func cancelButtonDidPress()
{
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func butCamera(sender: AnyObject)
{
let imagePickerController = ImagePickerController()
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
}
| mit | 88d8e5480ba8bf65c5399f28892386f1 | 23.755556 | 105 | 0.693447 | 4.730361 | false | false | false | false |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Home/Controller/HomeViewController.swift | 1 | 2620 | //
// HomeViewController.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/7/28.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
private let kPageTitleVH: CGFloat = 40
class HomeViewController: UIViewController,
PageTitleViewDelegate,
PageContentViewDelegate
{
// MARK: - 属性
private lazy var pageTitleV: PageTitleView = {
let v = PageTitleView(frame: CGRect(x: 0, y: kNavigationBarBottom, width: kScreenW, height: kPageTitleVH), titles: ["推荐", "游戏", "娱乐", "趣玩"])
v.delegate = self
return v
}()
private lazy var pageContentV: PageContentView = {
// 设置 frame
let frame = CGRect(x: 0, y: kNavigationBarBottom + kPageTitleVH, width: kScreenW, height: kScreenH - kNavigationBarBottom - kPageTitleVH - kTabBarH)
// 添加自控制器
var vcs = [UIViewController]()
vcs.append(RecommendViewController())
vcs.append(GameViewController())
vcs.append(AmuseViewController())
vcs.append(FunnyViewController())
let v = PageContentView(frame: frame, childVCs: vcs, parentVC: self)
v.delegate = self
return v
}()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
// MARK: - PageTitleViewDelegate
func pageTitleView(_ view: PageTitleView, didSelectedAt index: Int) {
pageContentV.setCurrentIndex(index)
}
// MARK: - PageContentViewDelegate
func pageContentVeiw(_ view: PageContentView, didScroll progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleV.scrollTitle(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
// MARK: - UI
private func setupUI() {
// 不自动调整 scrollView 的偏移量
automaticallyAdjustsScrollViewInsets = false
setupNavigationBar()
view.addSubview(pageTitleV)
view.addSubview(pageContentV)
}
private func setupNavigationBar() {
// 设置左侧 Item
navigationItem.leftBarButtonItem = UIBarButtonItem(normalImgName: "logo")
// 设置右侧 Items
navigationItem.rightBarButtonItems =
[UIBarButtonItem(normalImgName: "image_my_history", highlightImgName: "Image_my_history_click", width: 38),
UIBarButtonItem(normalImgName: "btn_search", highlightImgName: "btn_search_clicked", width: 38),
UIBarButtonItem(normalImgName: "Image_scan", highlightImgName: "Image_scan_click", width: 38)]
}
}
| mit | 1a6d592123cde72c23a826af20a3de24 | 32.513158 | 156 | 0.649391 | 4.743017 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGeneratorIntegrationTests/EndToEndIntegrationTestCase.swift | 1 | 12852 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import BazelIntegrationTestCase
@testable import TulsiGenerator
// Base class for end-to-end tests that generate xcodeproj bundles and validate them against golden
// versions.
class EndToEndIntegrationTestCase : BazelIntegrationTestCase {
enum Error: Swift.Error {
/// A subdirectory for the Xcode project could not be created.
case testSubdirectoryNotCreated
/// The Xcode project could not be generated.
case projectGenerationFailure(String)
/// Unable to execute user_build.py script.
case userBuildScriptInvocationFailure(String)
}
let extraDebugFlags = ["--define=TULSI_TEST=dbg"]
let extraReleaseFlags = ["--define=TULSI_TEST=rel"]
let fakeBazelURL = URL(fileURLWithPath: "/fake/tulsi_test_bazel", isDirectory: false)
let testTulsiVersion = "9.99.999.9999"
final func validateDiff(_ diffLines: [String], for resourceName: String, file: StaticString = #file, line: UInt = #line) {
guard !diffLines.isEmpty else { return }
let message = "\(resourceName) xcodeproj does not match its golden. Diff output:\n\(diffLines.joined(separator: "\n"))"
XCTFail(message, file: file, line: line)
}
final func diffProjectAt(_ projectURL: URL,
againstGoldenProject resourceName: String,
file: StaticString = #file,
line: UInt = #line) -> [String] {
guard let hashing = ProcessInfo.processInfo.environment["SWIFT_DETERMINISTIC_HASHING"],
hashing == "1" else {
XCTFail("Must define environment variable \"SWIFT_DETERMINISTIC_HASHING=1\", or golden tests will fail.")
return []
}
let goldenProjectURL = workspaceRootURL.appendingPathComponent(fakeBazelWorkspace
.resourcesPathBase,
isDirectory: true)
.appendingPathComponent("GoldenProjects/\(resourceName).xcodeproj", isDirectory: true)
guard FileManager.default.fileExists(atPath: goldenProjectURL.path) else {
assertionFailure("Missing required test resource file \(resourceName).xcodeproj")
XCTFail("Missing required test resource file \(resourceName).xcodeproj",
file: file,
line: line)
return []
}
var diffOutput = [String]()
let semaphore = DispatchSemaphore(value: 0)
let process = ProcessRunner.createProcess("/usr/bin/diff",
arguments: ["-r",
// For the sake of simplicity in
// maintaining the golden data, copied
// Tulsi artifacts are assumed to have
// been installed correctly.
"--exclude=.tulsi",
projectURL.path,
goldenProjectURL.path]) {
completionInfo in
defer {
semaphore.signal()
}
if let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) {
diffOutput = stdout.components(separatedBy: "\n").filter({ !$0.isEmpty })
} else {
XCTFail("No output received for diff command", file: file, line: line)
}
}
process.currentDirectoryPath = workspaceRootURL.path
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return diffOutput
}
final func copyOutput(source: URL, outputDir: String) throws {
if testUndeclaredOutputsDir != nil {
guard let testOutputURL = makeTestSubdirectory(outputDir,
rootDirectory: testUndeclaredOutputsDir,
cleanupOnTeardown: false) else {
throw Error.testSubdirectoryNotCreated
}
let testOutputProjURL = testOutputURL.appendingPathComponent(source.lastPathComponent)
if FileManager.default.fileExists(atPath: testOutputProjURL.path) {
try FileManager.default.removeItem(at: testOutputProjURL)
}
try FileManager.default.copyItem(at: source, to: testOutputProjURL)
}
}
final func validateBuildCommandForProject(_ projectURL: URL,
swift: Bool = false,
options: TulsiOptionSet = TulsiOptionSet(),
targets: [String]) throws {
let actualDebug = try userBuildCommandForProject(projectURL, release: false, targets: targets)
let actualRelease = try userBuildCommandForProject(projectURL, release: true, targets: targets)
let (debug, release) = expectedBuildCommands(swift: swift, options: options, targets: targets)
XCTAssertEqual(actualDebug, debug)
XCTAssertEqual(actualRelease, release)
}
final func expectedBuildCommands(swift: Bool,
options: TulsiOptionSet,
targets: [String]) -> (String, String) {
let provider = BazelSettingsProvider(universalFlags: bazelUniversalFlags)
let features = BazelBuildSettingsFeatures.enabledFeatures(options: options)
let dbg = provider.tulsiFlags(hasSwift: swift, options: options, features: features).debug
let rel = provider.tulsiFlags(hasSwift: swift, options: options, features: features).release
let config: PlatformConfiguration
if let identifier = options[.ProjectGenerationPlatformConfiguration].commonValue,
let parsedConfig = PlatformConfiguration(identifier: identifier) {
config = parsedConfig
} else {
config = PlatformConfiguration.defaultConfiguration
}
func buildCommand(extraBuildFlags: [String], tulsiFlags: BazelFlags) -> String {
var args = [fakeBazelURL.path]
args.append(contentsOf: bazelStartupOptions)
args.append(contentsOf: tulsiFlags.startup)
args.append("build")
args.append(contentsOf: extraBuildFlags)
args.append(contentsOf: bazelBuildOptions)
args.append(contentsOf: config.bazelFlags)
args.append(contentsOf: tulsiFlags.build)
args.append("--tool_tag=tulsi:user_build")
args.append(contentsOf: targets)
return args.map { $0.escapingForShell }.joined(separator: " ")
}
let debugCommand = buildCommand(extraBuildFlags: extraDebugFlags, tulsiFlags: dbg)
let releaseCommand = buildCommand(extraBuildFlags: extraReleaseFlags, tulsiFlags: rel)
return (debugCommand, releaseCommand)
}
final func userBuildCommandForProject(_ projectURL: URL,
release: Bool = false,
targets: [String],
file: StaticString = #file,
line: UInt = #line) throws -> String {
let expectedScriptURL = projectURL.appendingPathComponent(".tulsi/Scripts/user_build.py",
isDirectory: false)
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: expectedScriptURL.path) else {
throw Error.userBuildScriptInvocationFailure(
"user_build.py script not found: expected at path \(expectedScriptURL.path)")
}
var output = "<none>"
let semaphore = DispatchSemaphore(value: 0)
var args = [
"--norun",
]
if release {
args.append("--release")
}
args.append(contentsOf: targets)
let process = ProcessRunner.createProcess(
expectedScriptURL.path,
arguments: args,
messageLogger: localizedMessageLogger
) { completionInfo in
defer {
semaphore.signal()
}
let exitcode = completionInfo.terminationStatus
guard exitcode == 0 else {
let stderr =
String(data: completionInfo.stderr, encoding: .utf8) ?? "<no stderr>"
XCTFail("user_build.py returned \(exitcode). stderr: \(stderr)", file: file, line: line)
return
}
if let stdout = String(data: completionInfo.stdout, encoding: .utf8)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines),
!stdout.isEmpty {
output = stdout
} else {
let stderr =
String(data: completionInfo.stderr, encoding: .utf8) ?? "<no stderr>"
XCTFail("user_build.py had no stdout. stderr: \(stderr)", file: file, line: line)
}
}
process.currentDirectoryPath = workspaceRootURL.path
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return output
}
final func generateProjectNamed(_ projectName: String,
buildTargets: [RuleInfo],
pathFilters: [String],
additionalFilePaths: [String] = [],
outputDir: String,
options: TulsiOptionSet = TulsiOptionSet()) throws -> URL {
if !bazelStartupOptions.isEmpty {
let startupFlags = bazelStartupOptions.joined(separator: " ")
options[.BazelBuildStartupOptionsDebug].projectValue = startupFlags
options[.BazelBuildStartupOptionsRelease].projectValue = startupFlags
}
let debugBuildOptions = extraDebugFlags + bazelBuildOptions
let releaseBuildOptions = extraReleaseFlags + bazelBuildOptions
options[.BazelBuildOptionsDebug].projectValue = debugBuildOptions.joined(separator: " ")
options[.BazelBuildOptionsRelease].projectValue = releaseBuildOptions.joined(separator: " ")
let bazelURLParam = TulsiParameter(value: fakeBazelURL, source: .explicitlyProvided)
let config = TulsiGeneratorConfig(projectName: projectName,
buildTargets: buildTargets,
pathFilters: Set<String>(pathFilters),
additionalFilePaths: additionalFilePaths,
options: options,
bazelURL: bazelURLParam)
guard let outputFolderURL = makeXcodeProjPath(outputDir) else {
throw Error.testSubdirectoryNotCreated
}
let projectGenerator = TulsiXcodeProjectGenerator(workspaceRootURL: workspaceRootURL,
config: config,
extractorBazelURL: bazelURL,
tulsiVersion: testTulsiVersion)
// Bazel built-in preprocessor defines are suppressed in order to prevent any
// environment-dependent variables from mismatching the golden data.
projectGenerator.xcodeProjectGenerator.suppressCompilerDefines = true
// Don't update shell command utilities.
projectGenerator.xcodeProjectGenerator.suppressUpdatingShellCommands = true
// Don't install module cache pruner tool.
projectGenerator.xcodeProjectGenerator.suppressModuleCachePrunerInstallation = true
// The username is forced to a known value.
projectGenerator.xcodeProjectGenerator.usernameFetcher = { "_TEST_USER_" }
// Omit bazel output symlinks so they don't have unknown values.
projectGenerator.xcodeProjectGenerator.redactSymlinksToBazelOutput = true
let errorInfo: String
do {
let generatedProjURL = try projectGenerator.generateXcodeProjectInFolder(outputFolderURL)
try copyOutput(source: generatedProjURL, outputDir: outputDir)
return generatedProjURL
} catch TulsiXcodeProjectGenerator.GeneratorError.unsupportedTargetType(let targetType) {
errorInfo = "Unsupported target type: \(targetType)"
} catch TulsiXcodeProjectGenerator.GeneratorError.serializationFailed(let details) {
errorInfo = "General failure: \(details)"
} catch let error {
errorInfo = "Unexpected failure: \(error)"
}
throw Error.projectGenerationFailure(errorInfo)
}
}
| apache-2.0 | d8e1e9dc19a968ae41677fd476222037 | 46.6 | 138 | 0.629707 | 5.284539 | false | true | false | false |
thoughtworks/dancing-glyphs | GlyphWave/Configuration.swift | 1 | 1770 | /*
* Copyright 2016 Erik Doernenburg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use these files 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 ScreenSaver
class Configuration
{
enum WaveType: Int {
case linear, circular
}
static let sharedInstance = Configuration()
let numSprites = 600
let glyphSize = 0.1
let backgroundColor = NSColor.black
var defaults: UserDefaults
var waveType: WaveType = WaveType.linear
init()
{
let identifier = Bundle(for: Configuration.self).bundleIdentifier!
defaults = ScreenSaverDefaults(forModuleWithName: identifier)! as UserDefaults
defaults.register(defaults: [
String(describing: Wave.self): -1,
])
update()
}
var waveTypeCode: Int
{
set { defaults.set(newValue, forKey: String(describing: Wave.self)); update() }
get { return defaults.integer(forKey: String(describing: Wave.self)) }
}
private func update()
{
defaults.synchronize()
waveType = Util.enumForCode(waveTypeCode, defaultCase: WaveType.linear)
}
var wave: Wave
{
get
{
return (waveType == .linear) ? (LinearWave() as Wave) : (CircularWave() as Wave)
}
}
}
| apache-2.0 | 66bba1b73afca648e6fcab0a089230c7 | 25.41791 | 92 | 0.645198 | 4.317073 | false | false | false | false |
MukeshKumarS/Swift | test/expr/closure/basic.swift | 1 | 991 | // RUN: %target-parse-verify-swift
func takeIntToInt(f: (Int) -> Int) { }
func takeIntIntToInt(f: (Int, Int) -> Int) { }
// Simple closures
func simple() {
takeIntToInt({(x: Int) -> Int in
return x + 1
})
takeIntIntToInt({(x: Int, y: Int) -> Int in
return x + y
})
}
// Closures with variadic argument lists
func variadic() {
var f = {(start: Int, rest: Int...) -> Int in
var result = start
for x in rest {
result += x
}
return result
}
f(1)
f(1, 2)
f(1, 3)
let D = { (Ss ...) in 1 } // expected-error{{'...' cannot be applied to a subpattern which is not explicitly typed}}, expected-error{{unable to infer closure type in the current context}}
}
// Closures with attributes in the parameter list.
func attrs() {
_ = {(inout z: Int) -> Int in z }
}
// Closures with argument and parameter names.
func argAndParamNames() -> Int {
let f1: (x: Int, y: Int) -> Int = { (a x, b y) in x + y }
f1(x: 1, y: 2)
return f1(x: 1, y: 2)
}
| apache-2.0 | 30608b5dcf8225f05bb9021cba9eb594 | 22.595238 | 189 | 0.588295 | 3.087227 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorUIComponents/EditorUIComponents/MultipaneViewController.swift | 1 | 5475 | //
// MultipaneView.swift
// Editor
//
// Created by Hoon H. on 2015/02/04.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import AppKit.NSView
import AppKitExtras
//public protocol MultipaneViewControllerDelegate: class {
//// func multipaneViewController(MultipaneViewController, shouldSelectPaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, didSelectPaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, didHidePaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, willShowPaneAtIndex:Int)
//}
public final class MultipaneViewController: NSViewController {
// public weak var delegate:MultipaneViewControllerDelegate?
public var pageSelectionIndex:Int? = nil {
didSet {
_currentPageViewController = pageSelectionIndex == nil ? nil : self.pages[pageSelectionIndex!].viewController
}
}
public var pages:[Page] = [] {
willSet {
assert(pageSelectionIndex == nil, "You must set `pageSelectionIndex` to `nil` before removing selected page.")
_selectorSegmentView.segmentCount = 0
_selectorSegmentView.sizeToFit()
if self.pages.count == 0 {
pageSelectionIndex = nil
}
for p in self.pages {
assert(p.viewController.view.superview === self)
}
}
didSet {
for p in self.pages {
assert(p.viewController.view.superview === nil)
assert(p.viewController.view.translatesAutoresizingMaskIntoConstraints == false, "Page view MUST have `translatesAutoresizingMaskIntoConstraints` property set to `false`.")
}
_selectorSegmentView.segmentCount = pages.count
for i in 0..<pages.count {
let p = pages[i]
_selectorSegmentView.setLabel(p.labelText, forSegment: i)
}
_selectorSegmentView.sizeToFit()
}
}
////
public override func loadView() {
super.view = NSView()
}
public override func viewDidLoad() {
super.viewDidLoad()
_selectorSegmentView.controlSize = NSControlSize.SmallControlSize
_selectorSegmentView.segmentStyle = NSSegmentStyle.Automatic
_selectorSegmentView.font = NSFont.systemFontOfSize(NSFont.smallSystemFontSize())
_selectorSegmentView.sizeToFit()
let h = _selectorSegmentView.frame.size.height
_selectorStackView.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
_selectorStackView.setViews([_selectorSegmentView], inGravity: NSStackViewGravity.Center)
_selectorSegmentView.translatesAutoresizingMaskIntoConstraints = false
_selectorStackView.translatesAutoresizingMaskIntoConstraints = false
_contentHostingView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(_contentHostingView)
self.view.addSubview(_selectorStackView)
self.view.needsLayout = true
self.view.addConstraintsWithLayoutAnchoring([
_selectorStackView.centerXAnchor == self.view.centerXAnchor,
_selectorStackView.topAnchor == self.view.topAnchor,
_contentHostingView.leftAnchor == self.view.leftAnchor,
_contentHostingView.rightAnchor == self.view.rightAnchor,
_contentHostingView.topAnchor == _selectorStackView.bottomAnchor,
_contentHostingView.bottomAnchor == self.view.bottomAnchor,
])
self.view.addConstraints([
NSLayoutConstraint(item: _selectorSegmentView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: h)
])
////
_selectorSegmentView.sizeToFit()
_subcomponentDelegate = SubcomponentDelegate(owner: self)
_selectorSegmentView.target = _subcomponentDelegate
_selectorSegmentView.action = "onPageSelectorValueChanged:"
}
////
private let _selectorSegmentView = NSSegmentedControl()
private let _selectorStackView = NSStackView()
private let _contentHostingView = NSView()
private var _subcomponentDelegate = nil as SubcomponentDelegate?
private var _selectionConstraints = nil as [NSLayoutConstraint]?
private var _currentPageViewController:NSViewController? {
willSet {
if let vc = _currentPageViewController {
_contentHostingView.removeConstraints(_selectionConstraints!)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
_selectionConstraints = nil
}
}
didSet {
if let vc = _currentPageViewController {
assert(vc.view.translatesAutoresizingMaskIntoConstraints == false, "Selected view MUST have `translatesAutoresizingMaskIntoConstraints` property set to `false`.")
self.addChildViewController(vc)
_contentHostingView.addSubview(vc.view)
_selectionConstraints = _contentHostingView.addConstraintsWithLayoutAnchoring([
vc.view.centerAnchor == _contentHostingView.centerAnchor,
vc.view.sizeAnchor == _contentHostingView.sizeAnchor,
])
}
}
}
}
public extension MultipaneViewController {
public struct Page {
// public var icon:NSImage
public var labelText:String
public var viewController:NSViewController
public init(labelText:String, viewController:NSViewController) {
self.labelText = labelText
self.viewController = viewController
}
}
}
@objc
private final class SubcomponentDelegate: NSObject {
unowned let owner:MultipaneViewController
init(owner:MultipaneViewController) {
self.owner = owner
}
@objc
func onPageSelectorValueChanged(AnyObject?) {
let i = owner._selectorSegmentView.selectedSegment
let p = owner.pages[i]
owner._currentPageViewController = p.viewController
}
}
| mit | b911ad5677464e8cbfbdaef7ec3fd481 | 27.968254 | 207 | 0.760913 | 4.008053 | false | false | false | false |
wjk930726/weibo | weiBo/weiBo/iPhone/Modules/View/OAuthViewController/WBOAuthViewController.swift | 1 | 4413 | //
// WBOAuthViewController.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/26.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import SnapKit
import UIKit
class WBOAuthViewController: UIViewController {
lazy var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
lazy var webView: UIWebView = {
// let webView = UIWebView(frame: self.view.bounds)
let webView = UIWebView()
webView.scrollView.bounces = false
webView.scrollView.backgroundColor = UIColor.colorWithHex(hex: 0xEBEDEF)
webView.delegate = self
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension WBOAuthViewController {
func setupUI() {
view.backgroundColor = UIColor.white
navigationItem.leftBarButtonItem = leftBarButtonItem
view.addSubview(webView)
webView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.view)
if #available(iOS 11, *) {
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.topMargin)
make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottomMargin)
} else {
make.top.bottom.equalTo(self.view)
}
}
let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
if let url = URL(string: urlStr) {
webView.loadRequest(URLRequest(url: url))
}
}
}
extension WBOAuthViewController {
@objc fileprivate func cancel() {
dismiss(animated: true, completion: nil)
}
}
extension WBOAuthViewController: UIWebViewDelegate {
func webView(_: UIWebView, shouldStartLoadWith request: URLRequest, navigationType _: UIWebViewNavigationType) -> Bool {
if let url = request.url?.absoluteString {
if url.hasPrefix(redirectURI) {
if let query = request.url?.query {
if query.hasPrefix("code=") {
let code = String(query["code=".endIndex...])
NetworkManager.shared.requestForAccessToken(code: code, networkCompletionHandler: { obj in
guard let dictionary = obj, let access_token = dictionary["access_token"], let uid = dictionary["uid"] else {
console.debug("没有获得正确的access_token信息")
self.cancel()
return
}
let parameters = ["access_token": access_token, "uid": uid]
NetworkManager.shared.requestForUserInfo(parameters: parameters, networkCompletionHandler: { obj in
guard var responseObject = obj else {
console.debug("没有获得正确的userAccount信息")
self.cancel()
return
}
for (key, value) in dictionary {
responseObject[key] = value
}
WBUserAccountModel.shared.saveAccount(dictionary: responseObject)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: loginSuccess), object: self)
self.cancel()
// TODO: 如果登陆失败的提示没做
})
})
} else {
cancel()
}
}
return false
}
}
return true
}
func webViewDidFinishLoad(_ webView: UIWebView) {
view.backgroundColor = UIColor.colorWithHex(hex: 0xEBEDEF)
webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '[email protected]'")
}
}
| mit | ad76f207a98d9f82470b6df2f1480ee4 | 36.37931 | 137 | 0.549124 | 5.481669 | false | false | false | false |
kishikawakatsumi/TextKitExamples | Math/Math/ViewController.swift | 1 | 7571 | //
// ViewController.swift
// Math
//
// Created by Kishikawa Katsumi on 9/1/16.
// Copyright © 2016 Kishikawa Katsumi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label = UILabel()
let font = UIFont(name: "LatinModernMath-Regular", size: 20)!
override func viewDidLoad() {
super.viewDidLoad()
label.frame = CGRectInset(view.bounds, 10, 10)
label.numberOfLines = 0
view.addSubview(label)
let attributedText = NSMutableAttributedString()
attributedText.appendAttributedString(NSAttributedString(string: "The Quadratic Formula\n\n", attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(20)]))
attributedText.appendAttributedString(formula1())
attributedText.appendAttributedString(NSAttributedString(string: "\n"))
attributedText.appendAttributedString(NSAttributedString(string: "Standard Deviation and Variance\n\n", attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(20)]))
attributedText.appendAttributedString(formula2())
label.attributedText = attributedText
label.sizeToFit()
}
func formula1() -> NSAttributedString {
let formula = expression("x = -b \\pm \\sqrtb2-4ac2a")
.stringByAppendingString("".stringByPaddingToLength(5, withString: Symbols.horizontalLine, startingAtIndex: 0)) // line of sqrt
.stringByAppendingString("".stringByPaddingToLength(10, withString: Symbols.horizontalLine, startingAtIndex: 0)) // line of fraction
let range = NSRange(location: 0, length: formula.utf16.count)
let attributedText = NSMutableAttributedString(string: formula)
attributedText.setAttributes([NSFontAttributeName: UIFont(name: "LatinModernMath-Regular", size: 20)!], range: range)
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -12, range: NSRange(location: 0, length: 5)) // x = -b
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: 1, range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 2, range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -26, range: NSRange(location: 21, length: 3)) // 2a
attributedText.addAttribute(NSKernAttributeName, value: -68, range: NSRange(location: 19, length: 2)) // 2a
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 18, range: NSRange(location: 11, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: -12, range: NSRange(location: 22, length: 2)) // line of sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 14, range: NSRange(location: 24, length: 5)) // line of sqrt
attributedText.addAttribute(NSKernAttributeName, value: -135, range: NSRange(location: 28, length: 1)) // line of fraction
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -12, range: NSRange(location: 29, length: 10)) // line of fraction
let paragraghStyle = NSMutableParagraphStyle()
paragraghStyle.alignment = .Center
paragraghStyle.paragraphSpacing = 40
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraghStyle, range: NSRange(location: 0, length: attributedText.string.utf16.count))
return attributedText
}
func formula2() -> NSAttributedString {
let formula = expression("\\sigma = \\sqrt1N\(Symbols.horizontalLine)\\sum_i=1N (xi - \\mu)2")
.stringByAppendingString("".stringByPaddingToLength(9, withString: Symbols.horizontalLine, startingAtIndex: 0))
let range = NSRange(location: 0, length: formula.utf16.count)
let attributedText = NSMutableAttributedString(string: formula)
attributedText.setAttributes([NSFontAttributeName: font], range: range)
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 0, length: 5)) // z =
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 1, y: 2.4), range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 20, range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: 2, range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 6, length: 1)) // fraction of N
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -20, range: NSRange(location: 7, length: 2)) // fraction of N
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 7, length: 2)) // line of fraction
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 9, length: 1)) // line of fraction
attributedText.addAttribute(NSKernAttributeName, value: 4, range: NSRange(location: 9, length: 1)) // Sum
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 10, length: 1)) // Sum
attributedText.addAttribute(NSKernAttributeName, value: -20, range: NSRange(location: 10, length: 1)) // i=i
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 11, length: 4)) // i=i
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -24, range: NSRange(location: 11, length: 4)) // i=i
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 14, length: 1)) // N
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 15, length: 2)) // N
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 10, range: NSRange(location: 15, length: 2)) // N
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 21, length: 2)) // subscript i
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: -1, range: NSRange(location: 21, length: 2)) // subscript i
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 29, length: 1)) // superscript 2
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: 1, range: NSRange(location: 29, length: 1)) // superscript 2
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 18, length: 12)) // (xi - u)2
attributedText.addAttribute(NSKernAttributeName, value: -118, range: NSRange(location: 29, length: 1)) // line of sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 16, range: NSRange(location: 30, length: 9)) // line of sqrt
let paragraghStyle = NSMutableParagraphStyle()
paragraghStyle.alignment = .Center
paragraghStyle.paragraphSpacing = 40
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraghStyle, range: NSRange(location: 0, length: attributedText.string.utf16.count))
return attributedText
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 407ca48b99eaa5b7a5fa23f37a66140d | 59.079365 | 180 | 0.721268 | 4.67284 | false | false | false | false |
lixiangzhou/ZZLib | Source/ZZExtension/ZZUIExtension/UIColor+ZZExtension.swift | 1 | 5956 | //
// UIColor+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 17/3/12.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public extension UIColor {
/// 快速创建颜色
///
/// - parameter red: 红
/// - parameter green: 绿
/// - parameter blue: 蓝
/// - parameter alpha: 透明度
convenience init(red: Int, green: Int, blue: Int, alphaValue: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alphaValue)
}
/// 16进制rgb颜色值生成对应UIColor
///
/// - parameter stringHexValue: 16进制颜色值, 可包含前缀0x,#,颜色值可以是 RGB RGBA RRGGBB RRGGBBAA
convenience init?(stringHexValue: String) {
var hexValue = stringHexValue.zz_trim.uppercased()
if hexValue.hasPrefix("#") {
hexValue = String(hexValue[hexValue.index(hexValue.startIndex, offsetBy: 1)...])
} else if hexValue.hasPrefix("0X") {
hexValue = String(hexValue[hexValue.index(hexValue.startIndex, offsetBy: 2)...])
}
let len = hexValue.count
// RGB RGBA RRGGBB RRGGBBAA
if len != 3 && len != 4 && len != 6 && len != 8 {
return nil
}
var resultHexValue: UInt32 = 0
guard Scanner(string: hexValue).scanHexInt32(&resultHexValue) else {
return nil
}
var divisor: CGFloat = 255
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if len == 3 {
divisor = 15
r = CGFloat((resultHexValue & 0xF00) >> 8) / divisor
g = CGFloat((resultHexValue & 0x0F0) >> 4) / divisor
b = CGFloat( resultHexValue & 0x00F) / divisor
a = 1
} else if len == 4 {
divisor = 15
r = CGFloat((resultHexValue & 0xF000) >> 12) / divisor
g = CGFloat((resultHexValue & 0x0F00) >> 8) / divisor
b = CGFloat((resultHexValue & 0x00F0) >> 4) / divisor
a = CGFloat(resultHexValue & 0x000F) / divisor
} else if len == 6 {
r = CGFloat((resultHexValue & 0xFF0000) >> 16) / divisor
g = CGFloat((resultHexValue & 0x00FF00) >> 8) / divisor
b = CGFloat(resultHexValue & 0x0000FF) / divisor
a = 1
} else if len == 8 {
r = CGFloat((resultHexValue & 0xFF000000) >> 24) / divisor
g = CGFloat((resultHexValue & 0x00FF0000) >> 16) / divisor
b = CGFloat((resultHexValue & 0x0000FF00) >> 8) / divisor
a = CGFloat(resultHexValue & 0x000000FF) / divisor
}
self.init(red: r, green: g, blue: b, alpha: a)
}
/// 16进制rgb颜色值生成对应UIColor
///
/// - parameter hexValue: 16进制颜色值, 前缀0x开头的颜色值
convenience init?(hexValue: Int) {
self.init(stringHexValue: String(hexValue, radix: 16))
}
/// 随机色
static var zz_random: UIColor {
let red = arc4random() % 256
let green = arc4random() % 256
let blue = arc4random() % 256
return UIColor(red: Int(red), green: Int(green), blue: Int(blue))
}
/// 返回颜色的rgba值
var rgbaValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 24) + (green << 16) + (blue << 8) + alpha
return String(value, radix: 16)
}
return nil
}
var rgbValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: nil) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 16) + (green << 8) + blue
return String(value, radix: 16)
}
return nil
}
/// 返回颜色的rgba值
var rgbaHexStringValue: (red: String, green: String, blue: String, alpha: String)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = String(Int(r * 255), radix: 16)
let green = String(Int(g * 255), radix: 16)
let blue = String(Int(b * 255), radix: 16)
let alpha = String(Int(a * 255), radix: 16)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
/// 返回颜色的rgba值,0-255
var rgbaIntValue: (red: Int, green: Int, blue: Int, alpha: Int)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
}
| mit | 29cffcd71f68fe9ecdc0ad6b400ddfea | 32.261628 | 123 | 0.503234 | 3.751475 | false | false | false | false |
ZackKingS/Tasks | task/Classes/Others/Lib/TakePhoto/PhotoAlbumsTableViewController.swift | 2 | 4968 | //
// PhotoAlbumsTableViewController.swift
// PhotoPicker
//
// Created by liangqi on 16/3/5.
// Copyright © 2016年 dailyios. All rights reserved.
//
import UIKit
import Photos
class PhotoAlbumsTableViewController: UITableViewController,PHPhotoLibraryChangeObserver{
// 自定义需要加载的相册
var customSmartCollections = [
PHAssetCollectionSubtype.smartAlbumUserLibrary, // All Photos
PHAssetCollectionSubtype.smartAlbumRecentlyAdded // Rencent Added
]
// tableCellIndetifier
let albumTableViewCellItentifier = "PhotoAlbumTableViewCell"
var albums = [ImageModel]()
let imageManager = PHImageManager.default()
override func viewDidLoad() {
super.viewDidLoad()
// 9.0以上添加截屏图片
if #available(iOS 9.0, *) {
customSmartCollections.append(.smartAlbumScreenshots)
}
PHPhotoLibrary.shared().register(self)
self.setupTableView()
self.configNavigationBar()
self.loadAlbums(replace: false)
}
deinit{
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
func photoLibraryDidChange(_ changeInstance: PHChange) {
self.loadAlbums(replace: true)
}
private func setupTableView(){
self.tableView.register(UINib.init(nibName: self.albumTableViewCellItentifier, bundle: nil), forCellReuseIdentifier: self.albumTableViewCellItentifier)
// 自定义 separatorLine样式
self.tableView.rowHeight = PhotoPickerConfig.AlbumTableViewCellHeight
self.tableView.separatorColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.15)
self.tableView.separatorInset = UIEdgeInsets.zero
// 去除tableView多余空格线
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
}
private func loadAlbums(replace: Bool){
if replace {
self.albums.removeAll()
}
// 加载Smart Albumns All Photos
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
for i in 0 ..< smartAlbums.count {
if customSmartCollections.contains(smartAlbums[i].assetCollectionSubtype){
self.filterFetchResult(collection: smartAlbums[i])
}
}
// 用户相册
let topUserLibarayList = PHCollectionList.fetchTopLevelUserCollections(with: nil)
for i in 0 ..< topUserLibarayList.count {
if let topUserAlbumItem = topUserLibarayList[i] as? PHAssetCollection {
self.filterFetchResult(collection: topUserAlbumItem)
}
}
self.tableView.reloadData()
}
private func filterFetchResult(collection: PHAssetCollection){
let fetchResult = PHAsset.fetchAssets(in: collection, options: PhotoFetchOptions.shareInstance)
if fetchResult.count > 0 {
let model = ImageModel(result: fetchResult as! PHFetchResult<AnyObject> as! PHFetchResult<PHObject>, label: collection.localizedTitle, assetType: collection.assetCollectionSubtype)
self.albums.append(model)
}
}
private func configNavigationBar(){
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(PhotoAlbumsTableViewController.eventViewControllerDismiss))
self.navigationItem.rightBarButtonItem = cancelButton
}
func eventViewControllerDismiss(){
PhotoImage.instance.selectedImage.removeAll()
self.navigationController?.dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albums.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.albumTableViewCellItentifier, for: indexPath) as! PhotoAlbumTableViewCell
let model = self.albums[indexPath.row]
cell.renderData(result: model.fetchResult as! PHFetchResult<AnyObject>, label: model.label)
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.showDetailPageModel(model: self.albums[indexPath.row])
}
private func showDetailPageModel(model: ImageModel){
let layout = PhotoCollectionViewController.configCustomCollectionLayout()
let controller = PhotoCollectionViewController(collectionViewLayout: layout)
controller.fetchResult = model.fetchResult
self.navigationController?.show(controller, sender: nil)
}
}
| apache-2.0 | 49e9acad29179a4cd83e196fc76c245e | 34.456522 | 192 | 0.676885 | 5.25 | false | false | false | false |
jgonfer/JGFLabRoom | JGFLabRoom/Controller/HomeViewController.swift | 1 | 5395 | //
// ViewController.swift
// JGFLabRoom
//
// Created by Josep Gonzalez Fernandez on 13/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController {
let kTagRemoveLabel = 101
let kHeightCell: CGFloat = 55.0
let headers = ["Information Access", "Performance", "Security", "Miscellaneous", ""]
let results = [["EventKit", "OAuth"], ["Grand Central Dispatch"], ["Common Crypto", "Keychain", "Touch ID"], ["My Apps"], ["Clear Cache"]]
var indexSelected: NSIndexPath?
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
setupController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupController() {
Utils.registerStandardXibForTableView(tableView, name: "cell")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let indexSelected = indexSelected else {
return
}
let title = results[indexSelected.section][indexSelected.row]
let vc = segue.destinationViewController
vc.title = title
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return results.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return kHeightCell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "cell"
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
let title = results[indexPath.section][indexPath.row]
if indexPath.section == 4 {
// First we search in the current cell for the label
if let view = cell!.viewWithTag(kTagRemoveLabel) {
// If the label exists, we remove it before add it again
view.removeFromSuperview()
}
// We customize our Delete Cache cell (It'll be different from the others
let removeLabel = UILabel(frame: cell!.frame)
removeLabel.frame.size = CGSizeMake(CGRectGetWidth(removeLabel.frame), kHeightCell)
removeLabel.text = title
removeLabel.textColor = UIColor.redColor()
removeLabel.textAlignment = .Center
removeLabel.tag = kTagRemoveLabel
// Finally we add it to the cell
cell!.addSubview(removeLabel)
cell!.accessoryType = .None
} else {
cell!.textLabel!.text = title
cell!.accessoryType = .DisclosureIndicator
}
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
indexSelected = indexPath
let row = indexPath.row
switch indexPath.section {
case 0:
sectionSelectedInformationAccess(row)
case 1:
sectionSelectedPerformance(row)
case 2:
sectionSelectedSecurity(row)
case 3:
sectionSelectedMiscellaneous(row)
case 4:
ImageHelper.sharedInstance.cleanCache()
default:
break
}
}
// MARK: Sections Selection
private func sectionSelectedInformationAccess(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdEventKit, sender: tableView)
case 1:
performSegueWithIdentifier(kSegueIdSocial, sender: tableView)
break
default:
break
}
}
private func sectionSelectedPerformance(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdGCD, sender: tableView)
default:
break
}
}
private func sectionSelectedSecurity(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdCommonCrypto, sender: tableView)
case 1:
performSegueWithIdentifier(kSegueIdKeychain, sender: tableView)
case 2:
performSegueWithIdentifier(kSegueIdTouchID, sender: tableView)
default:
break
}
}
private func sectionSelectedMiscellaneous(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdListApps, sender: tableView)
default:
break
}
}
}
| mit | 8fa79fa206af7658c675cbb4ae625321 | 31.107143 | 142 | 0.616611 | 5.63048 | false | false | false | false |
johnlui/JSONNeverDie | Example/JSONNeverDieExample/ViewController.swift | 1 | 2675 | //
// ViewController.swift
// JSONNeverDieExample
//
// Created by 吕文翰 on 15/9/27.
// Copyright © 2015年 JohnLui. All rights reserved.
//
import UIKit
import JSONNeverDie
class People: JSONNDModel {
@objc var name = ""
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let json = JSONND(string: "{\"name\": \"JohnLui\"}")
let people = People(JSONNDObject: json)
print(people.name)
if let url = URL(string: "http://httpbin.org/get?hello=world"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let json1 = JSONND(string: string)
print(json1["args"]["hello"].stringValue)
print(json1.RAW)
}
if let url = URL(string: "http://httpbin.org/get?hello=world"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let json = JSONND(string: string)
print("json string: \(json.RAWValue)")
print("GOT string for key 'hello': ", json["args"]["hello"].stringValue)
}
// init from array
let array = ["hello", 123, false] as [Any]
let arrayJSON = JSONND(array: array as [AnyObject])
print(arrayJSON.array?.first?.string)
print(arrayJSON.array?[1].int)
print(arrayJSON.array?[2].bool)
print(arrayJSON.RAW)
// init from dictionary
let dic = ["hello": "NeverDie", "json": 200] as [String : Any]
let dicJSON = JSONND(dictionary: dic as [String : AnyObject])
print(dicJSON["hello"].string)
print(dicJSON["json"].int)
print(dicJSON.RAW)
if let url = Bundle.main.url(forResource: "Model", withExtension: "json"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let jsonForModel = JSONND(string: string)
let model = Model(JSONNDObject: jsonForModel)
print(model.string)
print(model.double)
print(model.int)
print(model.array_values.first)
print(model.array.first?.key)
print(model.hey.man.hello)
}
self.testReflection()
}
func testReflection() {
let json = JSONND(dictionary: ["name": "JohnLui" as AnyObject])
let people = People(JSONNDObject: json)
print(people.name) // get "JohnLui"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 2612c446e8b9b6095cbdc65b6f4accf8 | 31.91358 | 88 | 0.579145 | 4.165625 | false | false | false | false |
attheodo/ATHExtensions | ATHExtensions/ATHExtensions.swift | 1 | 4232 | //
// ATHExtensions.swift
// ATHExtensions
//
// Created by Athanasios Theodoridis on 25/05/16.
//
//
import Foundation
public struct App {
// MARK: - Private Properties
/// NSUserDefaults key for storing whether app has run before
private static let kATHExtensionsHasAppRunBeforeKey = "kATHExtensionsHasAppRunBefore"
// MARK: - Public Properties
/// Returns an optional string containing `CFBundleDisplayName`
public static var bundleDisplayName: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") as? String
}
/// Returns an optional string containing `CFBundleName`
public static var bundleName: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String
}
/// Returns the app's version number (`CFBundleShortVersionString`)
public static var version: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
}
/// Returns the app's build number (`kCFBundleVersionKey`)
public static var buildNumber: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as? String
}
/// Returns the app's version and build number
public static var versionWithBuildNumber: String? {
guard let version = self.version, buildNumber = self.buildNumber else {
return nil
}
if version == buildNumber {
return "v\(version)"
} else {
return "v\(version) (b\(buildNumber))"
}
}
/// Returns a boolean indicating whether "Debug" configuration is active
public static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
/// Returns a boolean indicating whether a production configuration is active
public static var isRelease: Bool {
return !isDebug
}
/// Returns a boolean indicating whether the app is currently being run in unit-testing mode
public static var isBeingTested: Bool {
return NSProcessInfo.processInfo().environment["XCInjectBundle"] != nil
}
/// returns a boolean indicating whether the apps is currently being run in UI testing mode
public static var isBeingUITested: Bool {
return NSProcessInfo.processInfo().arguments.contains("-ui_testing")
}
/// Returns a boolean indicating whether the app is running on the simulator
public static var isRunningOnSimulator: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return false
#endif
}
/// Returns a boolean indicating whether the app is running on a device
public static var isRunningOnDevice: Bool {
return !isRunningOnSimulator
}
/// A reference to the application delegate
public static var delegate: UIApplicationDelegate? {
return UIApplication.sharedApplication().delegate
}
/// Returns a boolean indicating whether this is the first time ever
/// the app is running
public static var isFirstLaunch: Bool {
let d = NSUserDefaults.standardUserDefaults()
if d.boolForKey(kATHExtensionsHasAppRunBeforeKey) {
return false
} else {
d.setBool(true, forKey: kATHExtensionsHasAppRunBeforeKey)
d.synchronize()
return true
}
}
/// Returns a boolean indicating whether this is the first time ever
/// the current version of the app is running
public static var isFirstLaunchForCurrentVersion: Bool {
guard let version = self.version else {
return true
}
let d = NSUserDefaults.standardUserDefaults()
let key = "\(kATHExtensionsHasAppRunBeforeKey)\(version)"
if d.boolForKey(key) {
return false
} else {
d.setBool(true, forKey: key)
d.synchronize()
return true
}
}
}
| mit | 56fd6e1aa7c07059455a5ee708986cf4 | 30.117647 | 105 | 0.629726 | 5.32327 | false | false | false | false |
devedbox/AXBadgeView-Swift | Sources/BadgeView.swift | 1 | 19194 | //
// BadgeView.swift
// Badge
//
// The MIT License (MIT)
//
// Copyright (c) 2016 devedbox.
//
// 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
// MARK: - Types.
extension BadgeView {
// MARK: Style.
/// The style of the badge view.
public enum Style {
case normal // Shows a red dot only.
case number(value: Int) // Shows a number text.
case text(value: String) // Shows a custom text.
case new // Shows a 'new' text.
}
// MARK: Animator.
/// The animation type of the badge view.
public enum Animator: String {
case none // None animator, badge view stay still.
case scale // Sacle animator
case shaking // Shake animator.
case bounce // Bounce animator.
case breathing // Breathing animator.
}
// MARK: Offset.
/// The offset of a rectangle at any size.
public enum Offset {
case least
case exact(CGFloat)
case percent(CGFloat)
case greatest
}
/// The offsets of the badge view.
public struct Offsets {
public var x: Offset
public var y: Offset
public static func offsets(
x: Offset,
y: Offset) -> Offsets
{
return Offsets(x: x, y: y)
}
}
}
// MARK: - BadgeViewDelegate.
public protocol BadgeViewDelegate {
/// Badge view property.
var badge: BadgeView { get set }
/// Animated to show the badge view.
func showBadge(animated: Bool)
/// Animated to hide the badge view.
func clearBadge(animated: Bool)
}
extension BadgeViewDelegate {
public func showBadge(
animated: Bool,
configuration: (BadgeView) -> Void = { _ in })
{
configuration(badge)
showBadge(animated: animated)
}
}
// MARK: - UIView.
extension UIView: BadgeViewDelegate {
/// The associated keys.
private struct _AssociatedKeys {
/// Key for `badgeView`.
static var badge = "badgeKey"
}
/// Returns the badge view of the receiver.
public var badge: BadgeView {
get {
if self is BadgeView {
fatalError("The badge view of 'BadgeView' itself is not accessible.")
}
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
if self is BadgeView {
fatalError("The badge view of 'BadgeView' itself is not accessible.")
}
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
badge.show(
animated: animated,
inView: self
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - UIBarButtonItem.
extension UIBarButtonItem: BadgeViewDelegate {
private struct _AssociatedKeys {
static var badge = "badgeKey"
}
public var badge: BadgeView {
get {
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self, &_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
guard let view = value(forKey: "view") as? UIView else {
return
}
badge.show(
animated: animated,
inView: try! view.viewInEndpointsOfMinY()
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - UITabBarItem.
extension UITabBarItem: BadgeViewDelegate {
private struct _AssociatedKeys {
static var badge = "badgeKey"
}
public var badge: BadgeView {
get {
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
guard let view = value(forKey: "view") as? UIView else {
return
}
badge.show(
animated: animated,
inView: try! view.viewInEndpointsOfMinY()
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - AXBadgeView.
public class BadgeView: UILabel {
/// The mask of the badge view using shape layer.
public struct Mask {
/// The path content of the badge view's layer.
public private(set) var path: (CGRect) -> CGPath
public init(
path: @escaping (CGRect) -> CGPath)
{
self.path = path
}
fileprivate func _layer(
for frame: CGRect) -> CAShapeLayer
{
let layer = CAShapeLayer()
layer.fillColor = UIColor.black.cgColor
layer.path = path(frame)
return layer
}
// MARK: Presets.
public static let cornerRadius: Mask = Mask {
return UIBezierPath(
roundedRect: $0,
cornerRadius: $0.height * 0.5
).cgPath
}
public static func roundingCorner(
_ corner: UIRectCorner) -> Mask
{
return Mask {
return UIBezierPath(
roundedRect: $0,
byRoundingCorners: corner,
cornerRadii: CGSize(
width: $0.height * 0.5,
height: $0.height * 0.5
)
).cgPath
}
}
}
/// The attaching view of badge view.
public final weak var attachingView: UIView!
/// The alignment view of badge view.
public final weak var alignmentView: UIView!
/// Limited number to show text on .number style. Default is 99.
open var limitedNumber: Int = 99
/// Override text as unavailable, using style instead.
@available(*, unavailable)
public final override var text: String? {
get {
return super.text
}
set { }
}
/// The mask of the badge view.
public final var masking: Mask = .cornerRadius {
didSet {
setNeedsLayout()
}
}
/// The stroke color of the badge view.
open var strokeColor: UIColor? {
didSet {
setNeedsLayout()
}
}
/// The stroke appearance layer.
private lazy var _strokeLayer = CAShapeLayer()
/// Style of badge view. Defaults to AXBadgeViewNormal.
open var style = Style.normal {
didSet {
switch style {
case .normal:
super.text = ""
case .new:
super.text = "new"
case .number(value: let val):
if val > limitedNumber {
super.text = "\(limitedNumber)"+"+"
} else {
super.text = "\(val)"
}
case .text(value: let val):
super.text = val
}
sizeToFit()
if !constraints.contains(_widthLayout) {
addConstraint(_widthLayout)
}
if !constraints.contains(_heightLayout) {
addConstraint(_heightLayout)
}
_widthLayout.constant = bounds.width
_heightLayout.constant = bounds.height
setNeedsLayout()
if
visible,
scaleContent
{
show(animated: true)
}
if hideOnZero {
switch style {
case .number(value: let val) where val == 0:
isHidden = true
case .text(value: let val) where val.isEmpty:
isHidden = true
case .new: fallthrough
default: break
}
} else {
isHidden = false
}
}
}
/// Animation type of badge view. Defaults to None.
open var animator = Animator.none {
didSet {
layer.removeAllAnimations()
switch animator {
case .breathing:
layer.add(
createBreathingAnimation(duration: 1.2),
forKey: animator.rawValue
)
case .bounce:
layer.add(
createBounceAnimation(
repeatCount: .greatestFiniteMagnitude,
duration: 0.8,
fromLayer: layer
),
forKey: animator.rawValue
)
case .scale:
layer.add(
createScaleAnimation(
fromScale: 1.2,
toScale: 0.8,
duration: 0.8,
repeatCount: .greatestFiniteMagnitude
),
forKey: animator.rawValue
)
case .shaking:
layer.add(
createShakeAnimation(
repeatCount: .greatestFiniteMagnitude,
duration: 0.8,
fromLayer: layer
),
forKey: animator.rawValue
)
default: break
}
}
}
/// The offsets of the badge view laying on the attaching view.
/// Defaults to (x: .greatest, y: .least).
open var offsets = Offsets(x: .greatest, y: .least) {
didSet {
if
let suview = superview,
let align = alignmentView ?? superview
{
if
let _ = _horizontalLayout,
suview.constraints.contains(_horizontalLayout)
{
suview.removeConstraint(_horizontalLayout)
}
if
let _ = _verticalLayout,
suview.constraints.contains(_verticalLayout)
{
suview.removeConstraint(_verticalLayout)
}
switch offsets.x {
case .least, .exact(0.0), .percent(0.0):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .left,
multiplier: 1.0,
constant: 0.0
)
case .greatest, .exact(suview.bounds.width), .percent(1.0):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: 1.0,
constant: 0.0
)
case .exact(let val):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: val / suview.bounds.width,
constant: 0.0
)
case .percent(let val):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: max(0.0, min(1.0, val)),
constant: 0.0
)
}
switch offsets.y {
case .least, .exact(0.0), .percent(0.0):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .top,
multiplier: 1.0,
constant: 0.0
)
case .greatest, .exact(suview.bounds.height), .percent(1.0):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0
)
case .exact(let val):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: val / suview.bounds.height,
constant: 0.0
)
case .percent(let val):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: max(0.0, min(1.0, val)),
constant: 0.0
)
}
suview.addConstraint(_horizontalLayout)
suview.addConstraint(_verticalLayout)
suview.setNeedsDisplay()
}
}
}
/// Hide on zero content. Defaults to YES.
open var hideOnZero = true
/// Min size. Defaults to {12.0, 12.0}.
open var minSize = CGSize(width: 12.0, height: 12.0) {
didSet {
sizeToFit()
style = {
style
}()
}
}
/// Scale content when set new content to badge label. Defaults to false.
open var scaleContent = false
/// Is badge visible.
open var visible: Bool {
return (superview != nil && !isHidden && alpha > 0) ? true : false
}
private var _horizontalLayout: NSLayoutConstraint!
private var _verticalLayout : NSLayoutConstraint!
private lazy var _widthLayout = NSLayoutConstraint(
item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0
)
private lazy var _heightLayout = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0
)
convenience init()
{
self.init(frame:CGRect.zero)
}
override init(
frame: CGRect)
{
super.init(frame: frame)
initializer()
}
required public init?(
coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initializer()
}
deinit {
// Do something to dealloc.
}
/// Initializer.
fileprivate func initializer() -> Void {
translatesAutoresizingMaskIntoConstraints = false
font = UIFont.systemFont(ofSize: 12)
backgroundColor = UIColor.red
textColor = UIColor.white
textAlignment = NSTextAlignment.center
style = .normal
}
/// - override: sizeThatFits
override open func sizeThatFits(
_ size: CGSize) -> CGSize
{
var susize = super.sizeThatFits(size)
susize.width = max(susize.width + susize.height / 2, minSize.width)
susize.height = max(susize.height, minSize.height)
return susize
}
/// - override: layoutSubviews
public override func layoutSubviews() {
super.layoutSubviews()
_maskBadgeViewIfNeeded(with: masking)
_strokeEdgesOfBadgeViewIfNeeded(with: strokeColor?.cgColor)
}
/// - override: willMoveToSuperview
override open func willMove(
toSuperview newSuperview: UIView?)
{
super.willMove(toSuperview: newSuperview)
newSuperview.map { _ in
offsets = {
offsets
}()
}
alpha = 1.0
}
/// - override: didMoveToSuperview
override open func didMoveToSuperview() {
super.didMoveToSuperview()
if let suview = superview {
self.offsets = { offsets }()
if !suview.constraints.contains(_verticalLayout) {
suview.addConstraint(_verticalLayout)
}
if !suview.constraints.contains(_horizontalLayout) {
suview.addConstraint(_horizontalLayout)
}
suview.bringSubviewToFront(self)
}
}
/// Show badge view in a target view with animation.
///
/// - parameter animated: animated to show badge view or not.
/// - parameter inView: the target view to add badge view.
///
/// - returns: Void.
open func show(
animated:Bool,
inView attachingView: UIView? = nil,
alignTo alignmentView: UIView? = nil) -> Void
{
self.attachingView = attachingView
self.alignmentView = alignmentView ?? attachingView
self.attachingView?.addSubview(self)
self.attachingView?.clipsToBounds = false
isHidden ? isHidden = false : ()
alpha < 1.0 ? alpha = 1.0 : ()
transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.6,
options: AnimationOptions(rawValue: 7),
animations: {
self.transform = CGAffineTransform.identity
},
completion: nil
)
} else {
transform = CGAffineTransform.identity
}
}
/// Hide the badge view with animation.
///
/// - parameter animated: animated to hide or not.
/// - parameter completion: completion block call back when the badge view finished hiding.
///
/// - returns: Void.
open func hide(
animated: Bool,
completion: @escaping (() -> Void) = { }) -> Void
{
if animated {
UIView.animate(
withDuration: 0.35,
animations: {
self.alpha = 0.0
},
completion: { [unowned self] finished -> Void in
if finished {
self.removeFromSuperview()
self.alpha = 1.0
completion()
}
}
)
} else {
self.removeFromSuperview()
completion()
}
}
/// Mask the bdage view if needed.
private func _maskBadgeViewIfNeeded(
with masking: Mask)
{
layer.mask = masking._layer(for: bounds)
}
/// Stroke the badge view's edges if needed.
///
/// - Parameter strokeColor: The color of the strokes. Nil to ignore stroke.
private func _strokeEdgesOfBadgeViewIfNeeded(
with strokeColor: CGColor?)
{
if
let strokeColor = strokeColor
{
_strokeLayer.frame = bounds
_strokeLayer.path = masking.path(bounds.insetBy(dx: 0.5, dy: 0.5))
_strokeLayer.strokeColor = strokeColor
_strokeLayer.fillColor = nil
_strokeLayer.strokeStart = 0.0
_strokeLayer.strokeEnd = 1.0
_strokeLayer.lineWidth = 1.0
layer.addSublayer(_strokeLayer)
} else {
_strokeLayer.removeFromSuperlayer()
}
}
}
| mit | f23db86e4e6eb11a38d9b3922f5e72df | 24.090196 | 93 | 0.58388 | 4.464759 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.